我想将DRY快速应用于正在创建的行。如何重构此代码,以便调用闭包?它位于视图控制器上。
var topLineView: UIView = {
let lineView = UIView()
lineView.layer.borderWidth = 1.0
lineView.layer.borderColor = UIColor.lightGray.cgColor
return lineView
}()
var bottomLineView: UIView = {
let lineView = UIView()
lineView.layer.borderWidth = 1.0
lineView.layer.borderColor = UIColor.lightGray.cgColor
return lineView
}()
var centerLineView: UIView = {
let lineView = UIView()
lineView.layer.borderWidth = 1.0
lineView.layer.borderColor = UIColor.lightGray.cgColor
return lineView
}()
我尝试创建变量,但是导致错误:
let lineView = {
let lineView = UIView()
lineView.layer.borderWidth = 1.0
lineView.layer.borderColor = UIColor.lightGray.cgColor
return lineView
}
var centerLineView = lineView()
错误(无法推断闭包类型,等等。]
Swift无法推断闭包的返回类型,因此您需要提前告知它要返回UIView
。这样可以编译并正常运行。
let lineView = { () -> UIView in
let lineView = UIView()
lineView.layer.borderWidth = 1.0
lineView.layer.borderColor = UIColor.lightGray.cgColor
return lineView
}
var myViewFromClosure = lineView()
var myViewFromClosure2 = lineView()
var myViewFromClosure3 = lineView()
但是,在这种情况下,我个人会选择function
而不是closure
。像这样:
func lineViewFunc() -> UIView {
let lineView = UIView()
lineView.layer.borderWidth = 1.0
lineView.layer.borderColor = UIColor.lightGray.cgColor
return lineView
}
var myViewFromFunc = lineViewFunc()
var myViewFromFunc2 = lineViewFunc()
var myViewFromFunc3 = lineViewFunc()
只需提供足够的值即可正确推断类型。
任一:
let lineView: () -> UIView = {
let lineView = UIView()
lineView.layer.borderWidth = 1.0
lineView.layer.borderColor = UIColor.lightGray.cgColor
return lineView
}
var centerLineView = lineView()
或
let lineView: UIView = {
let lineView = UIView()
lineView.layer.borderWidth = 1.0
lineView.layer.borderColor = UIColor.lightGray.cgColor
return lineView
}()
var centerLineView = lineView