swiftafnetworkingconditional-binding

Optional Binding (String: AnyObject) to [String]


I have a JSON object/dictionary I retrieved from AFNetworking and I want to conditionally unwrap the key into an array of strings.

var person: [String : AnyObject] = ...

if let interests = person["interests"] as [String]{
   // Do something
}

I get the following error message: (String : AnyObject) is not convertible to [String]. I don't think I can typecast person to [String : Any] because it comes out as [String : AnyObject] from the AFNetworking framework. Any ideas would be appreciated.


Solution

  • Update your Xcode. You are using an old version. Prior to Xcode 6.1, String was not considered an object type: you had to use NSString instead:

    if let interests = person["interests"] as? [NSString] {
    

    Apple fixed that issue, so this now works with Xcode 6.1:

    if let interests = person["interests"] as? [String] {
    

    Since Swift is rapidly evolving, you are advised to keep up to date with the latest released verison of Xcode, which as of this writing is Xcode 6.1.1.