[swift-users] Unexpected Optional unwrapping in generic fn

Michael Gardner gardnermj at gmail.com
Sun May 15 18:13:37 CDT 2016


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?


More information about the swift-users mailing list