2017-05-06 2 views
0

일부 사용자 정의 객체에서 Swift Dictionary을 작성 중입니다.Swift 사전 표현

다음은 사전을 정의하는 곳입니다.

public class NACarDataPoint: NSObject { 

    var dataKey: String! 
    var dataValue: Any! 

    public override init() { 
     // generic initializer, generally designed to be overridden 
     super.init() 
    } 

    init(key: String, value: Any) { 
     self.dataKey = key 
     self.dataValue = value 
    } 
} 

I :

for dataPoint in dataPoints! { 
    carDictionary[dataPoint.value(forKey: dataPoint.dataKey)] 
} 

dataPoint는 다음과 같은 클래스의 인스턴스 아래 루프 var carDictionary:[String:Any] = Dictionary<String, Any>()

내가 내 사용자 지정 개체에서 사전을 채우기 위해 노력하고있어 어디 명백하게 다소 일반적인 오류 인 것처럼 보이는 것을 얻는 것

`Cannot subscript a value of type `[String : Any]` with an index of type `Any`?` 

그러나 Swift에서 사전 작성이 어떻게 작동하는지 이해하지 못했기 때문에 문제를 파악하지 못하게되었습니다. 누구나 제안 사항이 있습니까? 고맙습니다! 비슷한 문제를 가진

게시물 : String not convertible to [AnyObject]

Cannot subscript a value of type '[String : String]?' with an index of type 'String'

Cannot subscript a value of [AnyObject]? with an index of type Int

답변

0

당신은 핵심 첨자를 기대하고있어 가치를두고 있습니다. 배열과 유사

, 당신은이처럼 사전에 개체에 액세스 :

let myValue = myDictionary["myKey"] 

이 키 "의 mykey"를 가지고 사전에 객체를 검색합니다. 대신 사전에 값을 설정하려면, 다음과 같이 키 첨자에 할당 :

귀하의 경우
myDictionary["myKey"] = myValue 

, 그것은 보이는 당신의 데이터 포인트 클래스는 사전에서 사용할 수있는 키와 값 객체가 같은 :

for dataPoint in dataPoints! { 
    carDictionary[dataKey] = dataPoint.value(forKey: dataPoint.dataKey) 
}