我正在寻找Swift中等效的以下Obj-C代码:
- newInstanceOf:(id)classRef {
return [classRef new];
}
然后使用它:
id instance = [whatever newInstanceOf:NSArray.class]
[instance isKindOfClass:NSArray.class] == YES
我尝试过使用Swift模板:
func newSomething<T>(classRef:T.Type) -> T {
return classRef()
}
我收到错误:error: 'T' cannot be constructed because it has no accessible initializers
答案 0 :(得分:0)
您可以创建一个协议,作为可由void-argument初始化程序初始化的对象的类型约束,然后将您选择的类型扩展到此协议。
protocol SimplyInitializable {
init()
}
extension Int : SimplyInitializable { }
extension Double : SimplyInitializable { }
extension String : SimplyInitializable { }
struct MyStruct {
var myInt : Int
init() {
myInt = 0
}
}
extension MyStruct : SimplyInitializable { }
func newSomething<T: SimplyInitializable>(classRef: T.Type) -> T {
return classRef.init()
}
/* Examples */
var a = newSomething(Int)
var b = newSomething(Double)
var c = newSomething("".dynamicType)
var d = newSomething(MyStruct)
var e = newSomething(a.dynamicType)
print(a.dynamicType) // Int
print(b.dynamicType) // Double
print(c.dynamicType) // String
print(d.dynamicType) // MyStruct
print(e.dynamicType) // Int
答案 1 :(得分:0)
实际上在Swift中,并非所有类都保证有init()初始化器。它可以与NSObject类一起使用,因为NSObject确实有这个要求。
func newInstanceOf<T:NSObject>(aClass:T.Type) -> NSObject
{ return aClass.init() }
let string = newInstanceOf(NSString) // ""
let date = newInstanceOf(NSDate) // 2016-01-15 05:27:29 +0000