Tom Pitts
Tom Pitts

Reputation: 600

Value of Optional Type 'string?' not unwrapped?

I'm not really sure what the error is saying and what I need to do to fix it? I have tried using both the ! and ?.

Code:

var sceneData = NSData.dataWithContentsOfFile(path, options: .DataReadingMappedIfSafe, error: nil)

Thanks <3

Upvotes: 1

Views: 1873

Answers (2)

Kalenda
Kalenda

Reputation: 1927

Or you can use the ! to auto unwrap your optional when you are certain that it cannot be null.

var sceneData = NSData.dataWithContentsOfFile(path!, options: .DataReadingMappedIfSafe, error: nil)

Upvotes: 0

Antonio
Antonio

Reputation: 72750

I presume that path is an optional string (declared as String?), so you must unwrap it before providing it to the method. The safest way is using optional binding:

if let path = path {
    var sceneData = NSData.dataWithContentsOfFile(path, options: .DataReadingMappedIfSafe, error: nil)
}

however as far as I know, the dataWithContentsOfFile method is unavailable - you should use the object initialization counterpart instead:

if let path = path {
    var sceneData = NSData(contentsOfFile: path, options: .DataReadingMappedIfSafe, error: nil)
}

Upvotes: 1

Related Questions