You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Swift纯原生方案:非@objc协议中如何标记方法废弃?

Pure Swift Solution for Deprecating Protocol Methods Without @objc

Hey there! I totally get why you’d want to avoid adding @objc to your Swift protocol—it undermines the benefits of using pure Swift. Let’s work through fixing that deprecation error in your Dequeable protocol.

The Root of the Error

That error pops up because older Swift versions restricted @available usage to @objc protocol members, but modern Swift (4.2+) fully supports applying version availability attributes directly to pure Swift protocol methods. If you’re on an older Swift version or need a fallback, here are two solid fixes:


Solution 1: Directly Apply @available to the Protocol Method (Modern Swift)

In Swift 4.2 and later, you can add @available straight to the protocol method without needing @objc. Just make sure your project targets this version or newer. Here’s your updated protocol:

public protocol Dequeable {
    @available(iOS, deprecated: 10.0, obsoleted: 11.0, message: "Because! Use 'hasXib' instead.")
    func register(cellType: DequeableComponentIdentifiable.Type, hasNib: Bool)
    
    func register(cellType: DequeableComponentIdentifiable.Type, hasXib: Bool)
}

This works flawlessly—compilers will flag any usage of the deprecated hasNib method just like they would for @objc protocols.


Solution 2: Use a Protocol Extension for Deprecated Methods (Older Swift Versions)

If you’re stuck on an older Swift version where direct @available on protocol methods isn’t supported, move the deprecated method into a protocol extension and mark it there. Here’s how:

public protocol Dequeable {
    func register(cellType: DequeableComponentIdentifiable.Type, hasXib: Bool)
}

public extension Dequeable {
    @available(iOS, deprecated: 10.0, obsoleted: 11.0, message: "Because! Use 'hasXib' instead.")
    func register(cellType: DequeableComponentIdentifiable.Type, hasNib: Bool) {
        // Optional: Forward calls to the new method for backward compatibility
        register(cellType: cellType, hasXib: hasNib)
    }
}

This works because extensions let you add default implementations, and @available is fully supported on extension methods even in older Swift versions. Any type conforming to Dequeable will inherit the deprecated method, and the compiler will warn about its usage.


Quick Notes

  • If you go with Solution 2, you can mark the extension method as final (Swift 5.3+) to prevent conforming types from overriding the deprecated implementation.
  • Always test the deprecation warnings to make sure they trigger as expected for anyone using your protocol.

内容的提问来源于stack exchange,提问作者user1951992

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 04:25:52