Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot assign to property in protocol - Swift compiler error

Tags:

ios

swift

I'm banging my head against the wall with the following code in Swift. I've defined a simple protocol:

protocol Nameable {     var name : String { get set } } 

and implemented that with:

class NameableImpl : Nameable {     var name : String = "" } 

and then I have the following method in another file (don't ask me why):

func nameNameable( nameable: Nameable, name: String ) {     nameable.name = name } 

The problem is that the compiler gives the following error for the property assignment in this method:

cannot assign to 'name' in 'nameable'

I can't see what I'm doing wrong... The following code compiles fine:

var nameable : Nameable = NameableImpl() nameable.name = "John" 

I'm sure it's something simple I've overlooked - what am I doing wrong?

like image 404
olensmar Avatar asked Dec 02 '14 03:12

olensmar


1 Answers

@matt's anwer is correct.

Another solution is to declare Nameable as a class only protocol.

protocol Nameable: class { //               ^^^^^^^      var name : String { get set } } 

I think, this solution is more suitable for this case. Because nameNameable is useless unless nameable is a instance of class.

like image 114
rintaro Avatar answered Oct 12 '22 02:10

rintaro