.alloc()'在Swift中不可用:改为使用对象初始化器

时间:2015-10-30 12:47:03

标签: swift2

public func swiftObjWithDict(dict: NSDictionary, cos: AnyClass) -> AnyObject? {
    let obj: AnyObject = cls    // It’s cls() before, but in swift 2.0 it’s unavailable.
    let value = "xxx"
    let k = "created_at"
    obj.setValue(value, forKey: k)     // throw an error

}

错误是:

  

由于未捕获的异常'NSUnknownKeyException'而终止应用程序,原因:'[setValue:forUndefinedKey:]:此类与密钥created_at不符合密钥值编码。'

Swift 2.0中alloc()的替代方法是什么?

1 个答案:

答案 0 :(得分:1)

import Foundation

class A {
    func f() {
        print("A class")
    }
}
class B: A {
    override func f() {
        print("B class, child of ", terminator:"")
        super.f()
    }
}

func foo(cls: AnyClass)->AnyObject? {
    switch cls {
    case is B.Type:
        return B()
    case is A.Type:
        return A()
    default:
        return nil
    }
}

if let a = foo(A.self) as? A {
    a.f()
}

if let b = foo(B.self) as? B {
    b.f()
}

好的,这与编译器错误无关。函数中的参数dict是什么?它是字典(键值编码兼容)。再次检查您的代码,或解释我们,您正在尝试做什么......