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

前端 未结 3 1783
走了就别回头了
走了就别回头了 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:14

    If it is ok to remove the priceString from the protocol, and only have it in your extension, you can call the protocol extension by casting IceCream to a Product in a helper extension.

    @objc protocol Product {
        var price:Int { get }
    }
    
    extension Product {
        var priceString:String {
            return "$\(price)"
        }
    }
    
    // This is the trick
    // Helper extension to be able to call protocol extension from obj-c
    extension IceCream : Product {
        var priceString:String {
            return (self as Product).priceString
        }
    }
    
    @objc class IceCream: NSObject {
        var price: Int {
            return 2
        }
    }
    

提交回复
热议问题