Swift纯原生方案:非@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

