[swift-users] Unexpected Optional unwrapping in generic fn

Joe Groff jgroff at apple.com
Mon May 16 12:07:27 CDT 2016


> On May 15, 2016, at 4:13 PM, Michael Gardner via swift-users <swift-users at swift.org> wrote:
> 
> I'm having trouble understanding why the following code is trying to unwrap an Optional.
> 
> ////////
> 
> class Proxy<T> {
> 	var value:T
> 	init(_ value:T) {
> 		self.value = value
> 	}
> }
> 
> func setter<T>(p:Proxy<T>) -> Any? -> () {
> 	return {p.value = $0 as! T}
> }
> 
> var i = Proxy<Int?>(0), s = setter(i)
> 
> s(2)
> i.value // => 2
> s(nil) // => fatal error: unexpectedly found nil while unwrapping an Optional value
> 
> ////////
> 
> My understanding is that since T is `Int?` here, the setter should be doing (nil as! Int?), which doesn't cause an error. What am I missing?

You're right, it should be able to successfully cast a `nil` Any? to a nil `Int?. This is a bug. If you have time, could you write up a report on bugs.swift.org?

-Joe


> _______________________________________________
> swift-users mailing list
> swift-users at swift.org
> https://lists.swift.org/mailman/listinfo/swift-users



More information about the swift-users mailing list