digitalangel digitalangel - 5 months ago 14
Swift Question

Swift 2: !, ? -" Value of optional type "..." not unwrapped"


Value of optional type "..." not unwrapped; did you mean to use '!' or '?'?


Can someone explain me what this error message exactly means? When should I use '?' and when '!'?

Answer

obj?.fn() calls fn member function if the object isn't null, otherwise doesn't do anything.

obj!.fn() on the other hand asserts that obj isn't null, and calls fn. If the object is null, you get an exception.

So it's a difference in assertiveness: you either ask or simply claim the nullable property of a nullable object.