Skip to content

Instantly share code, notes, and snippets.

@kongtomorrow
Last active April 21, 2023 17:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kongtomorrow/8d1ac5161021451c794c to your computer and use it in GitHub Desktop.
Save kongtomorrow/8d1ac5161021451c794c to your computer and use it in GitHub Desktop.
you're freaking me out, Swift
func foo(f:()->(Int?)) {
println(f())
}
let bar : ()->Int = { 3 }
// foo shouldn't be able to take bar, should it?
foo(bar) // prints Optional(3)
// you're freaking me out, Swift. Did it allocate a wrapping closure?
// 'cause say we wanted to do the coercion by hand. We'd have to do this:
let coercedBar = { ()->Int? in return .Some(bar()) }
foo(coercedBar)
@tammofreese
Copy link

Isn't it beautiful that this works? The compiler could throw an error, and force you to code the wrapping manually. However, then we would be on a slippery slope to disallow implicit wrapping of non-optionals in optionals as well, as non-optional and optional type are totally different as well. Consider:

func foo(f: Int?) {
    println(f)
}
let bar: Int = 3
// Foo wants an optional int. That's a totally different type than a non-optional int.
// Still, this works (and should work) fine.
foo(bar) // prints Optional(3)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment