如何根據用戶提供的實例確定協議是否符合特定的子類型,如果這種方式不可行,則可以使用任何替代解決方案。在運行時確定協議類型
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