如何根据用户提供的实例确定协议是否符合特定的子类型,如果这种方式不可行,则可以使用任何替代解决方案。在运行时确定协议类型
API
protocol Super {}
protocol Sub: Super {} //inherited by Super protocol
class Type1: Super {} //conforms to super protocol
class Type2: Type1, Sub {} //conforms to sub protocol
内的另一个API类
func store(closures: [() -> Super]) {
self.closures = closures
}
时,它的时间打电话
func go() {
for closure in closures {
var instance = closure()
if instance is Super {
//do something - system will behave differently
} else { //it's Sub
//do something else - system will behave differently
}
}
}
用户的API
class Imp1: Type1 {}
class Imp2: Type2 {}
var closures: [() -> Super] = [ { Imp1() }, { Imp2() } ]
store(closures)
我的API中当前的解决方法
func go() {
for closure in closures {
var instance = closure()
var behavior = 0
if instance as? Type2 != nil { //not so cool, should be through protocols
behavior = 1 //instead of implementations
}
if behavior == 0 { //do something within the api,
} else { //do something else within the api
}
//instance overriden method will be called
//but not important here to show, polymorphism works in here
//more concerned how the api can do something different based on the types
}
}
为什么使用返回对象的函数数组而不是对象本身的数组? – lassej
不知道我是否有问题,用户实际上会提供他们自己的Parent和Child类的实现,编辑 – user2727195
是的,但函数可能是'func go(实例:[Super])',可能是calles用'go([Parent(),Child()])'。会更简单。 – lassej