如何将valueForKey的结果转换为swift中的正确类型?

时间:2014-09-04 15:31:08

标签: swift

我想在我的类中获取变量的值(作为字符串传递)并正确地进行转换。这是我到目前为止所做的。

// Playground - noun: a place where people can play

import UIKit

class Test: NSObject {
    var stringVar = "Some String"
    var arrayVar = ["Some", "Array"]

    override init() {
        super.init()

        var dynamicKey = "stringVar"
        var valueForKeyResult1: AnyObject! = valueForKey(dynamicKey)

        dynamicKey = "arrayVar"
        var valueForKeyResult2: AnyObject! = valueForKey(dynamicKey)

        var someVarName = valueForKeyResult2
    }
}

Test()

现在我如何获得var valueForKeyResult 1& 2首先将它们变成了它们的类型(不知道它们是什么类型)?

1 个答案:

答案 0 :(得分:0)

它们已经是正确的类型:

class Test: NSObject {
    var stringVar = "Some String"
    var arrayVar = ["Some", "Array"]

    override init() {
        super.init()

        var dynamicKey = "stringVar"
        var valueForKeyResult1: AnyObject! = valueForKey(dynamicKey)
        println("valueForKeyResult1: \(NSStringFromClass(valueForKeyResult1?.dynamicType)), value: \(valueForKeyResult1!)\n")

        dynamicKey = "arrayVar"
        var valueForKeyResult2: AnyObject! = valueForKey(dynamicKey)
        println("valueForKeyResult2: \(NSStringFromClass(valueForKeyResult2?.dynamicType)), value: \(valueForKeyResult2!)\n")
    }
}

Test()

输出:

  

valueForKeyResult1:Swift._NSContiguousString,value:Some String

     

valueForKeyResult2:_TtCSs23_ContiguousArrayStorage000000010050D510,值:(       一些,       排列   )