Swift AnyObject is not convertible to String/Int

后端 未结 4 1024
天命终不由人
天命终不由人 2020-12-29 19:42

I want to parse a JSON to object, but I have no idea how to cast AnyObject to String or Int since I\'m getting:

0x106bf1d07:  leaq   0x33130(%rip), %rax              


        
相关标签:
4条回答
  • 2020-12-29 20:11

    Now you just need to import foundation. Swift will convert value type(String,int) into object types(NSString,NSNumber).Since AnyObject works with all objects now compiler will not complaint.

    0 讨论(0)
  • 2020-12-29 20:29

    reminderJSON["id"] gives you an AnyObject?, so you cannot cast it to Int You have to unwrap it first.

    Do

    self.id = reminderJSON["id"]! as Int
    

    if you're sure that id will be present in the JSON.

    if id: AnyObject = reminderJSON["id"] {
        self.id = id as Int
    }
    

    otherwise

    0 讨论(0)
  • 2020-12-29 20:29

    This is actually pretty simple, the value can be extracted, casted, and unwrapped in one line: if let s = d["2"] as? String, as in:

    var d:[String:AnyObject] = [String:AnyObject]()
    d["s"] = NSString(string: "string")
    
    if let s = d["s"] as? String {
        println("Converted NSString to native Swift type")
    }
    
    0 讨论(0)
  • 2020-12-29 20:32

    In Swift, String and Int are not objects. This is why you are getting the error message. You need to cast to NSString and NSNumber which are objects. Once you have these, they are assignable to variables of the type String and Int.

    I recommend the following syntax:

    if let id = reminderJSON["id"] as? NSNumber {
        // If we get here, we know "id" exists in the dictionary, and we know that we
        // got the type right. 
        self.id = id 
    }
    
    if let receiver = reminderJSON["send_reminder_to"] as? NSString {
        // If we get here, we know "send_reminder_to" exists in the dictionary, and we
        // know we got the type right.
        self.receiver = receiver
    }
    
    0 讨论(0)
提交回复
热议问题