在实现类型时针对已弃用的 Swift 协议方法发出警告 [英] Emitting a warning for a deprecated Swift protocol method in implementing types

查看:33
本文介绍了在实现类型时针对已弃用的 Swift 协议方法发出警告的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Suppose I have a protocol with a bar() method that has a default implementation — essentially the Swift way of making a protocol requirement optional for implementing types:

protocol Foo {
    func bar()
}

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

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

Now suppose that I decide to rename that method barrrr(), because more rs are better:

protocol Foo {
    func barrrr()
}

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

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

Existing code may still implement the method with the old name:

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

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

This code thinks it’s customizing a Foo method, but it isn’t. Callers will look for barrrr(), and get the default implementation. Nobody calls bar().

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

I would therefore like to generate a warning for types that implement Foo and have a bar() method. This does not work:

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 无效.有没有办法做到这一点?它不需要是一个友好的警告;任何编译器错误就足够了.

Making the extension method final has no effect. Is there a way to do it? It needn’t be a friendly warning; any compiler error would suffice.

推荐答案

另一个答案,至少在 Swift 3 中不可能完全满足您的要求.

Without taking a position on whether it is a good thing, as suggested by another answer, exactly what you are asking for is not possible at least in Swift 3.

但是,正如我在回答相关问题时指出的那样,有可能弃用整个协议,并且这样做至少会给你在实现类型级别的弃用警告,如果不是在想要的属性/方法级别.

However, as I pointed out in response to a related question, it is possible to deprecate an entire protocol, and doing so would at least give you deprecation warnings at the implementing type level, if not precisely at the wanted property / method level.

这篇关于在实现类型时针对已弃用的 Swift 协议方法发出警告的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆