Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
318 views
in Technique[技术] by (71.8m points)

ios - Cannot assign to property in protocol - Swift compiler error

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

@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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...