是否可以从Objective-C调用Swift中协议扩展中定义的方法?
例如:
protocol Product {
var price:Int { get }
var priceString:String { get }
}
extension Product {
var priceString:String {
get {
return "$\(price)"
}
}
}
class IceCream : Product {
var price:Int {
get {
return 2
}
}
}
Run Code Online (Sandbox Code Playgroud)
实例的价格字符串IceCream是'$ 2'并且可以在Swift中访问,但是该方法在Objective-C中不可见.编译器抛出错误'No visible @interface for'FlowCream'声明选择器......'.
在我的配置中,如果方法是直接在Swift对象的实现中定义的,那么一切都按预期工作.即:
protocol Product {
var price:Int { get }
var priceString:String { get }
}
class IceCream : Product {
var price:Int {
get {
return 2
}
} …Run Code Online (Sandbox Code Playgroud) 我一直在玩协议扩展,我有一个问题.也许我想要实现的目标无法实现.我有这个游乐场:
//: Playground - noun: a place where people can play
import UIKit
protocol ArrayContainer {
typealias T
var array: [T] { get }
}
class MyViewController: UIViewController, ArrayContainer, UITableViewDataSource {
typealias T = String
var array = ["I am", "an Array"]
}
extension UITableViewDataSource where Self: ArrayContainer {
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return array.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
// …Run Code Online (Sandbox Code Playgroud)