[英]Cannot assign weak to custom array
I am getting this error 'weak' may only be applied to class and class-bound protocol types, not '[ExerciseSet]'
when trying to make a custom array object to weak.我收到此错误
'weak' may only be applied to class and class-bound protocol types, not '[ExerciseSet]'
尝试将自定义数组对象设置为弱时。 Why can't I assign weak to this type?为什么我不能将弱分配给这种类型?
class Session {
weak var sets: [ExerciseSet]?
}
You can't do this because Swift Arrays are structs, not classes.你不能这样做,因为 Swift 数组是结构,而不是类。 If you want to have a weak reference to an array in Swift, you will need to use a wrapper object like so:
如果你想在 Swift 中对数组进行弱引用,你将需要使用一个包装对象,如下所示:
class Wrapper<T> {
let value: T
}
then change your class to the following:然后将您的课程更改为以下内容:
class Session {
weak var sets: Wrapper<[ExerciseSet]?>
}
That being said, it probably doesn't make sense to use a weak reference here.话虽如此,在这里使用弱引用可能没有意义。 Your session is probably either a singleton or an object that stays in memory your entire application lifecycle.
您的会话可能是一个单例或一个在整个应用程序生命周期中都保留在内存中的对象。
Unless you actually need to know whether the property was set or not, you can also probably use [ExerciseSet]
instead of making it optional, then use an empty array when you don't have any values.除非您确实需要知道该属性是否已设置,否则您也可以使用
[ExerciseSet]
而不是将其设为可选,然后在没有任何值时使用空数组。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.