当我不想更改属性本身但该属性的属性时,是否可以使用具有类似函数参数let
的{{1}}属性?
e.g。
inout
此外,如果有更好的方法来设置一堆属性,当它们不在一个有用的循环中时也会以同样的方式设置。
答案 0 :(得分:3)
CAShapeLayer
是类,因此是引用类型。
let someLine = CAShapeLayer()
是对CAShapeLayer
对象的常量引用。
您只需将此引用传递给该函数即可
并修改函数中引用对象的属性。没有必要
对于&
运算符或inout
:
func setupLine(line: CAShapeLayer, startingPath: CGPath) {
line.path = startingPath
line.strokeColor = UIColor.whiteColor().CGColor
line.fillColor = nil
line.lineWidth = 1
}
let someLine = CAShapeLayer()
setupLine(someLine, startingPath: somePath)
可能的替代方案是便利初始化器
extension CAShapeLayer {
convenience init(lineWithPath path: CGPath) {
self.init()
self.path = path
self.strokeColor = UIColor.whiteColor().CGColor
self.fillColor = nil
self.lineWidth = 1
}
}
以便可以将图层创建为
let someLine = CAShapeLayer(lineWithPath: somePath)
游乐场的完整示例。请注意,它使用默认参数使其更加通用:
import UIKit
class ShapedView: UIView{
override var layer: CALayer {
let path = UIBezierPath(ovalInRect:CGRect(x:0, y:0, width: self.frame.width, height: self.frame.height)).CGPath
return CAShapeLayer(lineWithPath: path)
}
}
extension CAShapeLayer {
convenience init(lineWithPath path: CGPath, strokeColor:UIColor? = .whiteColor(), fillColor:UIColor? = nil, lineWidth:CGFloat = 1) {
self.init()
self.path = path
if let strokeColor = strokeColor { self.strokeColor = strokeColor.CGColor } else {self.strokeColor = nil}
if let fillColor = fillColor { self.fillColor = fillColor.CGColor } else {self.fillColor = nil}
self.lineWidth = lineWidth
}
}
let view = ShapedView(frame: CGRect(x:0, y:0, width: 100, height: 100))
结果为默认值: