swift - 在实现类型时针对已弃用的 Swift 协议(protocol)方法发出警告

标签 swift swift3

假设我有一个带有 bar() 方法的协议(protocol),该方法具有默认实现 — 本质上是使协议(protocol)要求对于实现类型可选的 Swift 方式:

protocol Foo {
    func bar()
}

extension Foo {
    func bar() {
        print("default bar() implementaion")
    }
}

现在假设我决定重命名该方法 barrrr(),因为越多 r 越好:

protocol Foo {
    func barrrr()
}

extension Foo {
    func barrrr() {
        print("default barrrr() implementaion")
    }
}

现有代码可能仍会使用旧名称实现该方法:

class Thinger: Foo {
    func bar() {
        print("custom bar() implementaion")
    }
}

这段代码认为它正在定制一个 Foo 方法,但它不是。调用者将查找 barrrr(),并获得默认实现。没有人调用 bar()

因此,我想为实现 Foo 并具有 bar() 方法的类型生成警告。这不起作用:

protocol Foo {
    func barrrr()

    @available(*, deprecated: 0.99, renamed: "barrrr()")
    func bar()
}

extension Foo {
    func barrrr() {
        print("default barrrr() implementaion")
    }

    func bar() {
        fatalError("renamed barrrr()")
    }
}

class Thinger: Foo {
    func bar() {   // No warning here!
        print("custom bar() implementaion")
    }
}

使扩展方法 final 无效。有办法吗?这不一定是一个友好的警告;任何编译器错误就足够了。

最佳答案

如果我正确理解了这个问题,我认为没有办法做到这一点——也不应该有。

你有一个协议(protocol),我们称它为 MyProtocol...

protocol MyProtocol {
    func myOldFunction()
}

extension MyProtocol {
    func myOldFunction() {
        print("doing my old things")
    }
}

在以后的版本中,您希望重命名协议(protocol)中的函数。

protocol MyProtocol {
    func myOldFunction() // now deprecated
    func myNewFunction()
}

在任何符合 MyProtocol 并实现了 myOldFunction() 的类上抛出弃用警告的主要问题是,实现函数和属性的类没有任何问题不是您的协议(protocol)的一部分。

这些方法或属性可能仍然是其他不关心您的协议(protocol)的事物所使用的完全有效的实现。

没有什么能阻止我们这样做:

protocol ViewControllerDeprecations {
    func viewDidLoad() // mark deprecated
    func viewWillAppear(Bool) // mark deprecated
    // etc., for all the life cycle methods
}

extension UIViewController: ViewControllerDeprecations {}

现在,所有包含上述代码文件的应用程序中的每个 UIViewController 子类都有这些愚蠢的弃用警告,只是因为您的特定协议(protocol)不再使用这些方法。

关于swift - 在实现类型时针对已弃用的 Swift 协议(protocol)方法发出警告,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39429824/

相关文章:

ios - 我们可以从第三方应用程序在 siri 中设置事件吗?

ios - swift 3.0 : Ambiguous reference to member 'Subscript' issue in push notification

swift - 命令因信号 : Segmentation fault: 11 when swift 3 migration 而失败

ios - 为什么 Collection View 中的动态集合单元格不显示为给定大小,并且在 swift 3 中滚动后会发生变化

swift - 如何导入特定网页上托管的特定 Swift 类/模块?

swift - 在 Swift 中更改消息 UIAlertController 的颜色

swift - 从收藏 View 自动播放下一个音频文件

swift - 如何转换数组类型?

ios - 我应该如何在 Swift 中创建一个依赖于另一个变量的变量?

ios - 防止 UIAlertController 在 UIAlertAction 上关闭