Reputation: 13
1.
protocol A: AnyObject { }
2.
protocol A { }
I know case 1
can limit class-type
But, why should I limit class-type?
Upvotes: 0
Views: 150
Reputation: 299345
AnyObject
requires that conforming types be classes, rather than structs or enums. See Class-Only Protocols for details.
Classes provide reference semantics, rather than value semantics, which you may require for your protocol. For example, if you want to observe an object, that only makes sense for a reference type (you can't observe changes to a value type, since value types are copied when modified). For more details on that see Structures and Classes, and particularly the sections explaining value and reference types.
There is no value type equivalent of AnyObject
. You can't require value semantics for a protocol. This can lead to some headaches. As an example of the difference, consider the following:
protocol Incrementing {
var value: Int { get set }
}
extension Incrementing {
func incremented() -> Self {
var new = self // Value types copy, reference types reference
new.value += 1
return new
}
}
struct S: Incrementing { var value: Int = 0 }
class C: Incrementing { var value: Int = 0 }
var s = S()
s.incremented().value // 1
s.value // 0
var c = C()
c.incremented().value // 1
c.value // 1 (!!!)
This code makes sense for a struct, but is buggy for a class. There's no real fix for that in Swift today.
Upvotes: 2