如何在 swift 中正确复制 CAShapeLayer?

How to properly copy CAShapeLayer in swift?

我正在尝试在 swift 中创建 CAShapeLayer 的副本,但我遇到了崩溃

Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[CAShapeLayer copyWithZone:]: unrecognized selector sent to instance 0x282e87e60'

我应该采取哪些额外步骤来允许 CALayer .copy() 工作而不会导致应用程序崩溃? 即使我不转换 .copy() 的结果,它仍然会在 copy() 行准确地失败...

private var drawLines: [CAShapeLayer]
func getCopiedLayers() -> [CAShapeLayer] {
    return drawLines.compactMap { layer -> CAShapeLayer? in
        return layer.copy() as? CAShapeLayer
    }
}

我做错了什么? 预先感谢您的回答

CALayer不符合API的NSCopying,但符合NSSecureCoding,所以可以添加如下复制能力

Tested with Xcode 11.2 / iOS 13.2 (with CAShapeLayer & CAGradientLayer)

extension CALayer : NSCopying {
    public func copy(with zone: NSZone? = nil) -> Any {
        if let data = try? NSKeyedArchiver.archivedData(withRootObject: self, requiringSecureCoding: false) {
            if let newInstance = try? NSKeyedUnarchiver.unarchiveTopLevelObjectWithData(data) {
                return newInstance
            }
        }
        fatalError() // << should never got here
    }
}

现在,可以无一例外地调用layer.copy()到任何层(理论上)。