2017-04-03 1 views
3
을 실패

I 놀이터에 다음 코드가 있습니다setValueForKeys는 스위프트

class Pokemon : NSObject { 

    var name :String! 
    var id :Int? 
    var imageURL :String! 
    var latitude :Double! 
    var longitude :Double! 

    init(dictionary :[String:Any]) { 

     super.init() 
     setValuesForKeys(dictionary) 
} 
} 

let dict :[String:Any] = ["name":"John","imageURL":"someimageURL","latitude":45.67] 
let pokemon = Pokemon(dictionary: dict) 

setValuesForKeys에 대한 호출 후 만들어가 다음과 같은 말에서 예외가 발생합니다 :

*** Terminating app due to uncaught exception 'NSUnknownKeyException', reason: '[<__lldb_expr_13.Pokemon 0x6000000ffd00> setValue:forUndefinedKey:]: this class is not key value coding-compliant for the key latitude.' 

내가 키가를 "위도"이지만 어떤 이유로 그것이 그것을 찾을 수 없습니다. 어떤 아이디어라도!

해결책 : 선택한 답변을 읽고 여기에 업데이트 된 코드 : 할 수 없습니다 코딩 그래서 키 - 값

class Pokemon : NSObject { 

    var name :String! 
    var id :Int = 0 
    var imageURL :String! 
    var latitude :Double = 0 
    var longitude :Double = 0 

    init(dictionary :[String:Any]) { 

     super.init() 
     setValuesForKeys(dictionary) 
} 
} 
+3

왜 그런 이니셜 라이저를 만드시겠습니까? 적절한 이니셜 라이저를 만들거나 속성을 직접 설정하지 않는 이유는 무엇입니까? – rmaddy

+0

절대적으로! 그러나 나는 위의 코드에서 내가 뭘 잘못하고 있는지 알아 내고 싶다. 또한이 이니셜 라이저는 많은 특성을 설정하는 데 도움이됩니다. –

+0

어때 [이 하나] (http://stackoverflow.com/q/26366082/3476191) 그럼? – NobodyNada

답변

5

유형 (유사 Double?) Double! 목적-C 세계에서 아무 대응이 없다, 그래서 it is not exposed as an Objective-C property "위도"라는 키를 찾아 충돌시킵니다.

KVC가 필요하면 해당 필드를 비표준으로 변환해야합니다.

class Pokemon : NSObject { 
    var name: String! 
    var id: Int = 0 
    var imageURL: String! 
    var latitude: Double = 0.0 
    var longitude: Double = 0.0 

    init(dictionary: [String: Any]) { 
     super.init() 
     setValuesForKeys(dictionary) 
    } 
} 
+0

그리고 끈! 또는 String? Objective-C 세계에서 서신을가집니다. –

+0

@johndoe 예, 그것들은 ObjC에서 NSMutableString *이됩니다. – kennytm