AnyObject to Array?

后端 未结 5 1984
既然无缘
既然无缘 2021-01-01 09:49

I\'m using NSJSONSerialization as so:

let twData: AnyObject? = NSJSONSerialization.JSONObjectWithData(responseData, options: NSJSONReadingOption         


        
相关标签:
5条回答
  • 2021-01-01 10:00

    This works in a playground:

    var data: Array<Dictionary<String,String>>? = twData as? Array<Dictionary<String, String>>
    

    the difference from your code is that twData does not require the ? at the end - it is an optional so the as? operator will take care of verifying that it can be case to an array of dictionaries - needless to say, if it's nil, as? will evaluate to nil

    0 讨论(0)
  • 2021-01-01 10:05

    As you already know it is a String type you are inserting to something transformable, please do:

    if let twoDataArray = twData as? Array<Dictionary<String, String>>{
       for data in twoDataArray{
           print(data)
       }
    }
    

    This will guard you from a crashing app when the dictionary is not of type <String,String>.

    0 讨论(0)
  • 2021-01-01 10:15

    Try the following, you can iterate through the array as given below.

    for element in twData as! Array<AnyObject> {
        print(element)
    }
    
    0 讨论(0)
  • 2021-01-01 10:15
    let twData: Any = NSJSONSerialization.JSONObjectWithData(responseData, options: NSJSONReadingOptions.MutableLeaves, error: &dataError)
    

    Do not use AnyObject. Use Any instead of AnyObject. It will work fine. AnyObject is for all reference type and Array is a value type. That's why this comes. Change it to Any.

    0 讨论(0)
  • 2021-01-01 10:17

    To cast your data to an array:

    var twDataArray = (twData as! NSArray) as Array
    

    The code above first casts twData to an NSArray, and then to an Array via a bridging cast. A bridging cast is a special type of cast which converts an Objective-C type to it's _ObjectiveCBridgeable conformant, Swift counterpart.

    (Note that I didn't need to write Array<AnyObject> because the element AnyObject is inferred in the bridging cast from NSArrayArray)

    Note that the cast above is a forced downcast. Only use this if you're absolutely sure that twData is going to be an instance of NSArray. Otherwise, use an optional cast.

    var twDataArray = (twData as? NSArray) as Array?
    
    0 讨论(0)
提交回复
热议问题