Reputation: 556
Im learning swift. I need to ask what is the real use of properties when it is declared in protocol ?
import UIKit
protocol parentProtocol
{
var firstName:String {get}
func fullName() -> String
}
class childClass:parentProtocol
{
var firstName = ""
func fullName() -> String {
firstName = "rajesh darak"
return firstName
}
}
var c = childClass()
c.fullName()
Though I'm declaring firstName
as get (i.e read only), in the function itself I'm able to change the value of firstName
.
Upvotes: 0
Views: 73
Reputation: 10091
The protocol parentProtocol
declares a requirement: anything that conforms to it must have a property firstName
that is gettable. It's not saying that anything that inherits must be only gettable.
Why would you want this behaviour? Well, it's kind of a design choice, but here's an example of where it's useful: CollectionType
. CollectionType
has a property count
. Now, for some of the operations you want to perform on CollectionType
s, you need to have access to count
. However, there's no need to confine things that inherit from it. For instance, Array
's count is read-only:
var ar = [1, 2, 3]
ar.count = 5 // What's supposed to happen here?!
But that doesn't mean that every CollectionType
has to have a read-only count. Repeat
, for instance has a variable count
:
var re = Repeat(count: 3, repeatedValue: 0) // [0, 0, 0]
re.count = 5 // [0, 0, 0, 0, 0]
And it makes total sense for you to be able to change it.
Upvotes: 1