Swift const 属性的 inout 参数

Swift inout parameter for const properties

当我不想更改 属性 本身但是 属性的属性?

例如

let someLine = CAShapeLayer()

func setupLine(inout line:CAShapeLayer, startingPath: CGPath) {
    line.path = startingPath
    line.strokeColor = UIColor.whiteColor().CGColor
    line.fillColor = nil
    line.lineWidth = 1
}

setupLine(&someLine, startingPath: somePath)

此外,如果有更好的方法可以在属性不在循环中时以相同的方式设置一堆属性,那也会有所帮助。

CAShapeLayer 是一个 class,因此是一个 引用类型.

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)

Playground 的完整示例。注意它使用默认参数使其更加通用:

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))

默认结果: