在我的应用程序内部,我创建了一个称为“位置”的协议,并扩展了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类,该方法更改了我添加的属性,但是编译器在我尝试修改属性值的那一行上给了我这个错误:
无法分配给属性:“自身”是不可变的
这是方法:
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
}
}
}
有人可以解释这个错误的本质吗?
答案 0 :(得分:4)
使协议成为参考类型
protocol Positions : class {