Why do I need to unwrap oneString
while I explicitly said it would not be nil when I declared it?
You’ve misunderstood what var oneString: String!
means. It does not mean oneString
will not be nil. If you declare a type as var oneString: String
, then you are declaring a type that cannot be nil.
The type String!
is an “implicitly-unwrapped optional”. That is, it’s an optional, much like String?
, but one that pretends to be a non-optional sometimes. Mostly for the purposes of reading it – you don’t have to explicitly unwrap it to get the value out. The downside being, if it is ever nil (and it totally can be), your code will trap and abort.
But this pretending-to-not-be-optional only goes so far. You cannot pass a String!
to a function as inout
when that argument is not an optional. Hence your problem.
Anton’s answer is completely correct in why it won’t work, and his suggested operator overload will make your code compile. But it isn’t the right solution – you should instead avoid using implicitly-unwrapped optionals as they are spring-loaded deathtraps and only to be used in specific circumstances (the most common being with Cocoa UI controls). 999 times out of 1,000 you would be better off with a regular optional or non-optional