檢查結構是否符合協議,但如果嵌套結構是可選的,它總是回傳false,
例子:
protocol XYZ {
}
extension XYZ {
func test() {
print("asdsfd")
}
}
struct Test1: XYZ {
var test2: Test2
var test3: Test3?
init(){
self.test2 = Test2()
self.test3 = Test3()
}
}
struct Test2: XYZ {
}
struct Test3: XYZ {
}
現在:如果我想檢查結構是否正在使用協議
let x = Test1()
以下條件將為真,因為Test2符合XYZ協議
print(type(of: x.test2) is XYZ.Type)
以下條件將是錯誤的,因為應該Optional<Test2>符合 協議,但由于可選,它會回傳XYZtruefalse
print(type(of: x.test3) is XYZ.Type)
在這種情況下我應該如何處理可選的,我嘗試通過展開可選但它沒有發生。任何幫助表示贊賞。
我試圖打開可選的包裝,但它沒有發生。我試圖找到一種方法來比較可選型別是否符合協議。
uj5u.com熱心網友回復:
請參閱The Swift Programming Language: Protocols: Checking for Protocol Conformance,其中is,as?和as!operators 可以直接檢查一致性,而無需提取type(of:):
檢查協議一致性
您可以使用型別轉換中描述的
isand運算子來檢查協議一致性,并轉換為特定協議。檢查并轉換為協議遵循與檢查型別并轉換為型別完全相同的語法:as
如果實體符合協議,則
is運算子回傳,否則回傳。truefalse向下轉換運算子的
as?版本回傳協議型別的可選值,nil如果實體不符合該協議,則該值是。向下轉換運算子的
as!版本強制向下轉換為協議型別,如果向下轉換不成功則觸發運行時錯誤。
所以,而不是:
print(type(of: x.test2) is XYZ.Type) // true
print(type(of: x.test3) is XYZ.Type) // false
您可以避免type(of:)并直接測驗一致性(處理可選):
print(x.test2 is XYZ) // true
print(x.test3 is XYZ) // true
uj5u.com熱心網友回復:
檢查協議一致性時不要使用Protocol.Type
protocol XYZ {
}
extension XYZ {
func test() {
print("asdsfd")
}
}
struct Test1: XYZ {
var test2: Test2
var test3: Test3?
init(){
self.test2 = Test2()
self.test3 = Test3()
}
}
struct Test2: XYZ {
}
struct Test3: XYZ {
}
let x = Test1()
// does Test1 conform to XYZ?
print(x is XYZ)
// Does x.test2 conform to the protocol?
print(x.test2 is XYZ)
// Does x.test3 conform to the protocol?
print(x.test3 is XYZ)
// The above prints true, we're seeing if it can be an XYZ, but if we test like you do
print(x.test3 is XYZ.Type)
// This is false, as you said in your example.
在您將要使用的真實編碼場景中
if let example = x.test3 as? MyProtocol { ... }
我想不出我遇到過需要與Protocol.Type.
此外,至少在這個例子中,不需要所有這些測驗,因為編譯器提前知道了。舉一個不會的例子:
let y: Any = x.test3
if let y = y as? XYZ {
print("Test")
}
這里編譯器不知道 y 符合協議,因為它的型別是Any,但我們可以嘗試轉換它 - 我們可以看到它確實有效。
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/536730.html
標籤:迅速快速协议
