Method parameter shadowing

12 views
Skip to first unread message

Boon

unread,
Jun 17, 2015, 1:52:07 PM6/17/15
to swift-l...@googlegroups.com

Swift allows you to shadow method parameter without providing any warning. 
In what circumstances would such a feature be useful? Also, this seems to go against the premise of Swift to promote safety.

var x:Int? = 3

func foo(x: Int?) {
    print(x)
    let x = 100  // shadowing parameter
    print(x)
}

Jim Dovey

unread,
Jun 17, 2015, 1:59:19 PM6/17/15
to Boon, swift-l...@googlegroups.com
I believe it’s by design, to ease working with Optionals. For instance, in v2 syntax, you can have the following to ‘promote’ an optional argument into a non-nil value:

func foo(x: Int?) -> Int? {
    guard let x = x else { return nil }
    return x + 10
}

--
You received this message because you are subscribed to the Google Groups "Swift Language" group.
To unsubscribe from this group and stop receiving emails from it, send an email to swift-languag...@googlegroups.com.
To post to this group, send email to swift-l...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/swift-language/e1bb6f31-b97b-485e-9a6c-e82ac2d62216%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Boon

unread,
Jun 17, 2015, 2:56:46 PM6/17/15
to swift-l...@googlegroups.com
That helps, thank you Jim.
Reply all
Reply to author
Forward
0 new messages