Reputation: 6359
I have an if statement where I would like to have two conditions like the following :
if let name = json["resource"]["fields"]["name"].stringValue && name.hasPrefix("/")
When I do that, I got an error "Use of unresolved identifier name". What's the solution then?
if let name = json["resource"]["fields"]["name"].stringValue && "test".hasPrefix("/"){
If I do this instead, I got an error "Optional type '$T16' cannot be used as a boolean; test for '!= nil' instead"
It's probably a stupid question but I must confess I'm lost...
Thanks for your help
Upvotes: 4
Views: 3543
Reputation: 130193
You aren't using a regular if statement, you're using optional binding, and you can't combine the binding with a check on the bound value like that. You could break it up to something like this though.
if let name = json["resource"]["fields"]["name"].stringValue {
if name.hasPrefix("/") {
// stuff
}
}
Edit: Looks like this has changed in Swift 1.2. According to the release notes, it's now possible to add extra conditions to the if let, while let statements:
The “if let” construct has been expanded to allow testing multiple optionals and guarding conditions in a single if (or while) statement using syntax similar to generic constraints:
if let name = json["resource"]["fields"]["name"].stringValue where name.hasPrefix("/") {
// stuff
}
The code above should achieve what you want. (Untested)
Upvotes: 6