0

当我不想更改属性本身但该属性的属性时,是否可以使用let具有类似功能参数的属性?inout

例如

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)

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

4

1 回答 1

3

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

let someLine = CAShapeLayer()

是对CAShapeLayer对象的常量引用。您可以简单地将此引用传递给函数并在函数内修改被引用对象的属性。不需要&运算符 or 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))

结果与默认值:

截屏

于 2016-06-02T19:09:59.947 回答