gpt4 book ai didi

const 属性的 Swift inout 参数

转载 作者:行者123 更新时间:2023-11-28 11:05:57 27 4
gpt4 key购买 nike

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

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com