Swift 3.将Any转换为符合特定协议的class
Swift 3. Cast Any to class which conforms specific protocol
我有一个随机协议作为例子
protocol testP {
init(param1: String)
}
我有一个class,以Any
为参数为例:
class testC {
var aClass: Any
}
如何检查 aClass
是否符合协议 testP
,如果符合,使用协议初始化程序创建一个新对象,例如:
let newObject = aClass(param1: "Hello World!")
求求你帮忙
您可以使用 if-let
:
将其作为其他类型检查进行测试
protocol TestP {
init(param1: String)
}
class TestC {
var aClass: Any
init(_ aClass: Any) {
self.aClass = aClass
}
}
class MyClassA: TestP {
required init(param1: String) {
//
}
}
class MyClassB {
}
let containerA = TestC(MyClassA.self)
let containerB = TestC(MyClassB.self)
if let testPType = containerA.aClass as? TestP.Type {
var a = testPType.init(param1: "abc")
print(a) //->MyClassA
}
if let testPType = containerB.aClass as? TestP.Type {
print("This print statement is not executed")
}
顺便说一句,如果您只将 class 类型分配给 aClass
,请考虑使用 AnyClass
或 Any.Type
。
我有一个随机协议作为例子
protocol testP {
init(param1: String)
}
我有一个class,以Any
为参数为例:
class testC {
var aClass: Any
}
如何检查 aClass
是否符合协议 testP
,如果符合,使用协议初始化程序创建一个新对象,例如:
let newObject = aClass(param1: "Hello World!")
求求你帮忙
您可以使用 if-let
:
protocol TestP {
init(param1: String)
}
class TestC {
var aClass: Any
init(_ aClass: Any) {
self.aClass = aClass
}
}
class MyClassA: TestP {
required init(param1: String) {
//
}
}
class MyClassB {
}
let containerA = TestC(MyClassA.self)
let containerB = TestC(MyClassB.self)
if let testPType = containerA.aClass as? TestP.Type {
var a = testPType.init(param1: "abc")
print(a) //->MyClassA
}
if let testPType = containerB.aClass as? TestP.Type {
print("This print statement is not executed")
}
顺便说一句,如果您只将 class 类型分配给 aClass
,请考虑使用 AnyClass
或 Any.Type
。