我们假设 myVar 在视图的每个实现中都具有相同的功能。我试图弄清楚如何声明/暴露某种 set-only 属性,而不是分配n次(每次创建新的 view ),但什么都没有来在我的头上。我怎么能重构成一条线呢?一次性任务?
errorPlacement: function(error, element) {
if ($(element).hasClass('className')) {
$('#myErrorLabel').one('focus', function() {
$(error).insertAfter('#someElement');
});
} else {
error.insertAfter(element);
}
}
答案 0 :(得分:2)
这样的东西,但是在数组中包含所有CustomViews
都是个好主意,也可以在这里实现
var a: (() -> Void)?
class CustomView: UIView {
var myVar: (() -> Void)?
}
class SomeClass {
let view1 = CustomView()
let view2 = CustomView()
let view3 = CustomView()
var myVar: (() -> Void)? {
set {
self.view2.myVar = newValue
self.view1.myVar = newValue
self.view3.myVar = newValue
}
get {
return self.myVar
}
}
}
let b = SomeClass()
b.myVar = ({print(3)})
b.view1.myVar!()
答案 1 :(得分:1)
这是你想要做的吗?
[someClass.view1, someClass.view2, someClass.view3].forEach { $0.myVar = self.myVar }
答案 2 :(得分:0)
这就是我倾向于处理这些问题的方法:
class OtherClass {
var text: String?
init(text: String?) {
self.text = text;
}
}
class TestClass {
var thing1: OtherClass?
var thing2: OtherClass?
var thing3: OtherClass?
var allTheThings: [OtherClass?] { return [thing1, thing2, thing3]}
var ownText: String? {
didSet {
allTheThings.forEach { $0?.text = ownText }
}
}
}
根据您希望更改的内容,您可以使数组属性在init中设置为常量而不是计算属性。
如果你想获得幻想,你也可以做这样的事情来设置:
private var allTheThings: [OtherClass?] {
get {
return [thing1, thing2, thing3]
}
set {
guard newValue.count == 3 else {
//probably should put an assertion in here
return
}
thing1 = newValue[0]
thing2 = newValue[1]
thing3 = newValue[2]
}
}
init() {
self.allTheThings = Array(repeating: OtherClass(text: "Test"), count: 3)
}