无法在协议中分配属性 - Swift编译器错误 [英] Cannot assign to property in protocol - Swift compiler error

查看:118
本文介绍了无法在协议中分配属性 - Swift编译器错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在用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 }
}

并通过以下方式实现:

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:


不能在'nameable'中指定'name'

我看不出我做错了什么。 ..以下代码编译正常:

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?

推荐答案

@ matt's anwer是正确的。

@matt's anwer is correct.

另一种解决方案是将可命名的声明为 class only protocol

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

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

我认为,这个解决方案更适合这种情况。因为 nameNameable 是无用的,除非 nameable class 的实例。

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

这篇关于无法在协议中分配属性 - Swift编译器错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆