提问者:小点点

无法分配给属性:“self”是不可变的swift错误


在我的应用程序中,我创建了一个名为“位置”的协议,并扩展了UIView类以符合该协议,以便向UIView类添加一些属性。我使用了下面的代码。

import Foundation
import UIKit

protocol Positions {
    var initialPositions: [CGRect] {get set}
    var finalPositions: [CGRect] {get set}
    var positionsAreDefined: Bool {get}
}

public enum PositionsType {
    case initial
}

private var initialPositionKey: UInt = 0
private var finalPositionKey: UInt = 0

extension Positions {
    var initialPositions: [CGRect] {
        get {
            if objc_getAssociatedObject(self, &initialPositionKey) != nil {
                return objc_getAssociatedObject(self, &initialPositionKey) as! [CGRect]
            } else {
                return [] as! [CGRect]
            }

        }
        set {
            objc_setAssociatedObject(self, &initialPositionKey, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
        }
    }

    var finalPositions: [CGRect] {
        get {
            if objc_getAssociatedObject(self, &finalPositionKey) != nil {
                return objc_getAssociatedObject(self, &finalPositionKey) as! [CGRect]
            } else {
                return [] as! [CGRect]
            }
        }

        set {
            objc_setAssociatedObject(self, &finalPositionKey, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
        }
    }

    var positionsAreDefined: Bool {
        get {return initialPositions.count != 0 && finalPositions.count != 0 && initialPositions.count == finalPositions.count}
    }

    var positionsCount: Int {
        get {return initialPositions.count}
    }
}

extension UIView: Positions {}

好吧,今天我尝试使用一个更改由我添加的属性的新方法来扩展UIView类,但编译器在我尝试修改属性值的行上给了我这个错误:

无法分配给属性:“self”是不可变的

方法是这样的:

public func horizontallyInContainer(withShift shift: CGFloat, forExpansionNumber index: Int, forPositionType type: PositionsType) {
    if self.positionsAreDefined && self.superview != nil {
        if type == .initial {

            var newPositions = self.initialPositions
            newPositions[index].origin.x = self.superview!.bounds.width * 0.5 - self.bounds.width + shift
            self.initialPositions = newPositions //Here happens the error

        } else {

            var newPositions = self.finalPositions
            newPositions[index].origin.x = self.superview!.bounds.width * 0.5 - self.bounds.width + shift
            self.finalPositions = newPositions //Also here happens

        }
    }
}

谁能给我解释一下这个错误的性质?


共1个答案

匿名用户

使协议成为引用类型

protocol Positions: AnyObject {