I was trying to test if two objects generated from a factory were identical, but the compiler does not seem to allow identity checking of objects that merely conform to the same protocol. Casting both objects to AnyObject seems fine however. Is there anyway to avoid what seems like unnecessary casting?
Here is a simple example the demonstrates what I am seeing (in swift 1.2)
protocol FooBar {
}
class Foo: FooBar {
}
class Bar {
let foo1: FooBar?
let foo2: FooBar?
init() {
foo1 = Foo()
foo2 = Foo()
if foo1! as? AnyObject === foo2! as? AnyObject { // this is fine
}
if foo1! === foo2! { // Birnary operator '===' cannot be applied to two FooBar operands
}
}
}
The protocol can then be adopted by a class, structure, or enumeration to provide an actual implementation of those requirements. But there would be a time when you want to restrict protocols to be adopted by a specific class. In Swift 5, you can do just that.
A protocol can require any conforming type to provide an instance property or type property with a particular name and type. The protocol doesn't specify whether the property should be a stored property or a computed property—it only specifies the required property name and type.
Protocols are used to define a “blueprint of methods, properties, and other requirements that suit a particular task or piece of functionality.” Swift checks for protocol conformity issues at compile-time, allowing developers to discover some fatal bugs in the code even before running the program.
Protocol composition is the process of combining multiple protocols into a single protocol. You can think of it as multiple inheritance. With protocol DoSomething , below, class HasSomethingToDo is able to do whatShouldBeDone and anotherThingToBeDone .
The identity operator ===
can only be applied to references, i.e. instances of classes.
If all types conforming to the FooBar
protocol are classes then
you can declare it as a "class protocol"
protocol FooBar : class { }
Then
if foo1! === foo2! { ... }
compiles and works as expected, because the compiler "knows" that both operands are references to a class instance.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With