Search code examples
arraysswiftanyobject

Swift: Thread 1: signal SIGABRT ( get child of AnyObject )


My code:

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"))!

After compile i get this error :

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


Solution

    • result["user"] is not AnyObject, according to the output it's clearly a dictionary ([String:Any])
    • userData["id"] is an Int

    The error occurs because you treat the number as String.

    One-liners seem to be cool but sometimes it's preferable to use a few lines more for better readability 😉

    let id : Int
    if let user = result["user"] as? [String:Any], userId = user["id"] as? Int {
        id = userId
    } else {
        id = 0
    }
    

    And for sake of coolness this is the one-liner

    let id = (result["user"] as? [String:Any])?["id"] as? Int ?? 0