Swift:线程 1:SIGABRT 信号(获取 AnyObject 的子对象)
Swift: Thread 1: signal SIGABRT ( get child of AnyObject )
我的代码:
let userData = result["user"] as? AnyObject // { test="x"; id=0; phone="none" }
var id = Int(userData?["id"] as? String ?? String(userData?["id"] as? String ?? "0"))!
编译后我得到这个错误:
2018-07-16 18:21:02.747944+0430 Matap[1550:415553] -[__NSCFNumber
length]: unrecognized selector sent to instance 0xb000000000000003
2018-07-16 18:21:02.748116+0430 Matap[1550:415553] * Terminating app
due to uncaught exception 'NSInvalidArgumentException', reason:
'-[__NSCFNumber length]: unrecognized selector sent to instance
0xb000000000000003'
* First throw call stack: (0x183c82d8c 0x182e3c5ec 0x183c90098 0x183c885c8 0x183b6e41c 0x105d9d5f4 0x105d36c68 0x106384478
0x1020a4aa0 0x10209f6cc 0x10208ac00 0x10676d1dc 0x10676d19c
0x106771d2c 0x183c2b070 0x183c28bc8 0x183b48da8 0x185b2d020
0x18db65758 0x1020c9098 0x1835d9fc0) libc++abi.dylib: terminating with
uncaught exception of type NSException
id 是 NSNumber
var id = (userData?["id"] as! NSNumber).stringValue // seems you consider it a string
result["user"]
不是 AnyObject
,根据输出它显然是一个字典 ([String:Any]
)
userData["id"]
是一个 Int
发生错误是因为您将数字视为字符串。
一行看起来很酷,但有时最好多使用几行以获得更好的可读性
let id : Int
if let user = result["user"] as? [String:Any], userId = user["id"] as? Int {
id = userId
} else {
id = 0
}
为了酷,这是单线
let id = (result["user"] as? [String:Any])?["id"] as? Int ?? 0
我的代码:
let userData = result["user"] as? AnyObject // { test="x"; id=0; phone="none" }
var id = Int(userData?["id"] as? String ?? String(userData?["id"] as? String ?? "0"))!
编译后我得到这个错误:
2018-07-16 18:21:02.747944+0430 Matap[1550:415553] -[__NSCFNumber length]: unrecognized selector sent to instance 0xb000000000000003 2018-07-16 18:21:02.748116+0430 Matap[1550:415553] * Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSCFNumber length]: unrecognized selector sent to instance 0xb000000000000003' * First throw call stack: (0x183c82d8c 0x182e3c5ec 0x183c90098 0x183c885c8 0x183b6e41c 0x105d9d5f4 0x105d36c68 0x106384478 0x1020a4aa0 0x10209f6cc 0x10208ac00 0x10676d1dc 0x10676d19c 0x106771d2c 0x183c2b070 0x183c28bc8 0x183b48da8 0x185b2d020 0x18db65758 0x1020c9098 0x1835d9fc0) libc++abi.dylib: terminating with uncaught exception of type NSException
id 是 NSNumber
var id = (userData?["id"] as! NSNumber).stringValue // seems you consider it a string
result["user"]
不是AnyObject
,根据输出它显然是一个字典 ([String:Any]
)userData["id"]
是一个Int
发生错误是因为您将数字视为字符串。
一行看起来很酷,但有时最好多使用几行以获得更好的可读性
let id : Int
if let user = result["user"] as? [String:Any], userId = user["id"] as? Int {
id = userId
} else {
id = 0
}
为了酷,这是单线
let id = (result["user"] as? [String:Any])?["id"] as? Int ?? 0