Can Swift Method Defined on Extensions on Protocols Accessed in Objective-c

前端 未结 3 1782
走了就别回头了
走了就别回头了 2021-01-03 21:57

Is it possible to call methods defined in a protocol extension in Swift from Objective-C?

For example:

protocol Product {
    var price:Int { get }
          


        
3条回答
  •  醉酒成梦
    2021-01-03 22:32

    Protocol extension does not work with @objc protocol, however you can extend the class in swift as a workaround.

    @objc protocol Product {
       var price: NSNumber? { get }
       var priceString:String { get }
    }
    
    ...
    // IceCream defined in Objective-C that does not extend Product
    // but has @property(nonatomic, strong, nullable) (NSNumber*)price
    // to make it confirm to Product
    ...
    extension IceCream: Product {
       var priceString:String {
          get {
            return "$\(price ?? "")"
          }
       }
    }
    

    This code is not clean at all, but it works.

提交回复
热议问题