I am trying to load a file from my app bundle in Swift 3, and I came across a weird situation with the Swift type inferencing. If I use the following code, I get an error on the third line that says Value of optional type "String?" not unwrapped
.
let url = NSURL(fileURLWithPath:Bundle.main.bundlePath)
let url2 = url.appendingPathComponent("foo.txt")
let path:String = url2?.path
To fix the error I unwrap the value on the third line by changing it to:
let path:String = url2?.path!
I now get the error Cannot force unwrap value of a non-optional type 'String'
. It seems like Swift can't determine whether the path property is a String
or a String?
. The autocomplete feature in Xcode says it is a String
, but the docs say it is a String?
.
The suggested fix by Xcode for the first error was to replace url2?.path
with (url2?.path)!
, which finally ended up working, but I have no idea why this works and the other ways don't.
let path:String = (url2?.path)!
What is going on? Is this a type inference bug in Swift, or am I missing something super obvious
In Swift, Optional chaining like:
... is interpreted as:
As you see the type of
path
is non-OptionalString
, so the expression causes error.(
url2
's type isURL?
, so the type of propertypath
isString
, notString?
.)This is not a direct answer to your question, but I would re-write your code as:
Shorter, and no worry about Optionals.