2017-11-15 3 views
1
protocol A { } 
class B: A { } 

func f(x: Any) { 
    print(x is A) 
} 
let x: B? = B() 
f(x: x) // false 

Ich würde erwarten, dass dies stattdessen true ist. Ist es ein Fehler in Swift?Swift Beliebiges Methodenargument Protokollkonformität Verloren

Die folgenden Beispiele funktionieren und das Rück true:

// 1 
func f(x: Any) { 
    print(x is A) 
} 
let x: B = B() // not optional 
f(x: x) // true 

// 2 
func f(x: Any) { 
    print(x is B) // check for B 
} 
let x: B? = B() 
f(x: x) // true 
+1

Yup, [dies ist ein Fehler] (https://bugs.swift.org/browse/SR-6279). – Hamish

Antwort

0

Wenn Sie testen möchten, ob Ihre Instanz zu Protokoll A entspricht können Sie entweder:

func<T>(x: T) { 
    print(x is A) 
} 

oder beide Funktionen in Verbindung verwenden:

func(x: Any) { 
    print(x is A) 
} 

func(x: Optional<Any>) { 
    print(x is A) 
} 
Verwandte Themen