Amir_P Amir_P - 1 year ago 216
iOS Question

Could not cast value of type '_SwiftValue' error

I'm trying to fill my arrays with datas in

that i get from server and I'm doing that with this code(swift 3 Xcode 8):

func parseReservationJson(_ anyObject:Array<AnyObject>){
for anyObj in anyObject{
let client_name = (anyObj["client_name"] as? String) ?? ""
let client_family = (anyObj["client_family"] as? String) ?? ""
let ft_of_time = ((anyObj["ft_of_time"] as AnyObject as! NSString).substring(to: 5) as NSString)

But I'm getting this error for the last line of
statement :

Could not cast value of type '_SwiftValue' (0x112d8a898) to 'NSString' (0x11003eab8).

I don't want to use dependency for converting JSON. what is wrong?

Answer Source

The error reason is that Swift 3 AnyObject? cannot be casted directly to Foundation NSString.

You could write

let ft_of_time = ((anyObj["ft_of_time"] as! String as NSString).substring(to: 5) as NSString)

But I recommend to replace the entire line with

let ftOfTime = anyObj["ft_of_time"] as! String
let ft_of_time = ftOfTime.substring(to:ftOfTime.index(ftOfTime.startIndex, offsetBy: 5)) as NSString

It does the same but it uses native Swift API. Except the final cast to NSString (if needed at all) there is no type casting back and forth.