const 属性的 Swift inout 参数

标签 swift pass-by-reference inout

是否可以使用 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)

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

最佳答案

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)

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

默认结果:

screenshot

关于const 属性的 Swift inout 参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37600124/

相关文章:

ios - 按顺序重复运行两个 SKActions?

objective-c - 如何在 Swift 中将 Objc-C NSUInteger[] = {0,1,2} 表示为 UnsafeMutablePointer<UInt>?

string - 在函数调用中发送 QString 的最佳方法是什么?

c++——消失的变量

ios - 快速在 View Controller 之间通过引用传递数组

Swift:带有 inout 闭包的函数

swift - NSPredicate 获取属性不在给定数组中的实体

ios - 解析 : log out anonymous user when user force terminates app

vhdl - 避免在 VHDL 中使用 inout

swift 3 更新 swift 2 的语法