swift 协议“弱"不能应用于非类类型 [英] swift protocol 'weak' cannot be applied to non-class type

查看:71
本文介绍了swift 协议“弱"不能应用于非类类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有点困惑.protocol A : class { ... }protocol A{ ... } 有什么区别,我们应该在 swift 中使用哪一个?

I'm a bit confused. What's the difference between protocol A : class { ... } and protocol A{ ... }, and which one we should use in swift?

PS:我们这样写的时候出错了

PS: we got an error when we wrote like this

protocol A{ ... }

weak var delegate: A

错误:'weak' 不能应用于非类类型

error : 'weak' cannot be applied to non-class type

推荐答案

protocol A : class { ... }

定义一个"class-only protocol":仅类类型(而不是结构或枚举)可以采用此协议.

defines a "class-only protocol": Only class types (and not structures or enumerations) can adopt this protocol.

弱引用仅针对引用类型定义.班级是引用类型,结构和枚举是值类型.(闭包也是引用类型,但闭包不能采用协议,因此它们在此上下文中无关紧要.)

Weak references are only defined for reference types. Classes are reference types, structures and enumerations are value types. (Closures are reference types as well, but closures cannot adopt a protocol, so they are irrelevant in this context.)

因此,如果符合协议的对象需要存储在弱属性中,那么该协议必须是仅类协议.

Therefore, if the object conforming to the protocol needs to be stored in a weak property then the protocol must be a class-only protocol.

这是另一个需要仅类协议的示例:

Here is another example which requires a class-only protocol:

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

func foo(a : A) {
    a.name = "bar" // error: cannot assign to property: 'a' is a 'let' constant
}

这不会编译,因为对于结构和枚举的实例,a.name = "bar"a 的变异.如果你定义协议为

This does not compile because for instances of structures and enumerations, a.name = "bar" is a mutation of a. If you define the protocol as

protocol A : class { 
    var name : String { get set }
}

然后编译器知道 a 是一个类类型的实例a 是对象存储的引用,并且 a.name = "bar" 修改引用的对象,但不修改 a.

then the compiler knows that a is an instance of a class type to that a is a reference to the object storage, and a.name = "bar" modifies the referenced object, but not a.

所以一般来说,如果需要,你会定义一个仅限类的协议采用协议的类型是引用类型而不是值类型.

So generally, you would define a class-only protocol if you need the types adopting the protocol to be reference types and not value types.

这篇关于swift 协议“弱"不能应用于非类类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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