Kumar Utsav Kumar Utsav -3 years ago 121
Swift Question

Expected else after guard statement, but else is there, why is it complaining?

I am trying to do PropertyListSerialization as opposed to using just NSDictionary(contentsOfFile:) so I changed my code for that. Now using guard , I have to give else , I am providing else, what mistake am I making in this line of code. It says "Expected 'else' after 'guard' condition. This line of code when using NSDictionary(contentsOfFile:) was working fine , but this change to PropertyListSerialization is not working for me. I am pasting the code.



guard
let filePathValue = filePath,
// let fileContentDictionary:NSDictionary = NSDictionary(contentsOfFile: filePathValue)
let data = try? Data(contentsOf: filePathValue as URL),

let result = try? PropertyListSerialization.propertyList(from: data, options: [], format: nil) as? [[String:Any]]
print(result!)

else{
return
}





enter image description here

Answer Source

You can access the result after that else block also if your response is dictionary then you need to cast the result of propertyList(from:options:format:) to [String:Any] not the [[String:Any]] because it is dictionary.

guard let filePathValue = filePath,
    //let fileContentDictionary: NSDictionary = NSDictionary(contentsOfFile: filePathValue)
    let data = try? Data(contentsOf: filePathValue as URL),
    let result = try? PropertyListSerialization.propertyList(from: data, options: [], format: nil) as? [String:Any] //not [[String:Any]]
else {
    return
}
//Result is still optional
print(result!)

Now as of you have used try? your result is still optional so if you want result as non-optional then use () with try? like this.

guard let filePathValue = filePath,
    //let fileContentDictionary: NSDictionary = NSDictionary(contentsOfFile: filePathValue)
    let data = try? Data(contentsOf: filePathValue as URL),
    let result = (try? PropertyListSerialization.propertyList(from: data, options: [], format: nil)) as? [String:Any] //not [[String:Any]]
else {
    return
}
//Now result is non-optional
print(result)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download