从 C 导入的扩展结构

Extension struct imported from C

我是 Swift 的新手,我有这个扩展:

extension UIView.KeyframeAnimationOptions {
    init(animationOptions: UIView.AnimationOptions) {
        rawValue = animationOptions.rawValue
    }
}

自 Swift 4.2 rawValue = animationOptions.rawValue 产生此警告:

Initializer for struct 'UIView.KeyframeAnimationOptions' must use "self.init(...)" or "self = ..." because the struct was imported from C

我使用这样的扩展名:

UIView.animateKeyframes(withDuration: 1.2, delay: 0.0, options: [.repeat, UIView.KeyframeAnimationOptions(animationOptions: .curveEaseOut)], animations: {
...
}

如何修复来自 struct was imported from C 的警告消息?

您的代码从来都不正确。应该是:

extension UIView.KeyframeAnimationOptions {
    init(animationOptions: UIView.AnimationOptions) {
        self.init(rawValue: animationOptions.rawValue)
    }
}

但是,这是个坏主意。您正在将一个枚举的选项强制为不相关的枚举。这会导致问题。

这样做的目的是限制跨模块的结构初始化器。这加强了初始化结构的安全性。

Swift structs are designed to be flexible and their implementation could be changed between releases. Since initializers have to initialize every stored property, they have two options:

  • Assign each property before returning or using self.
  • Assign all properties at once by using self.init(…) or self = ….

The former requires knowing every stored property in the struct. If all of those properties happen to be public, however, a client in another target can implement their own initializer, and suddenly adding a new stored property (public or not) becomes a source-breaking change.

您可以在此处找到更多详细信息 here

Swift 4.1 开始,您的代码应如下所示:

extension UIView.KeyframeAnimationOptions {
    init(animationOptions: UIView.AnimationOptions) {
        self = .init(rawValue: animationOptions.rawValue)
    }
}