Ios Swift:覆盖属性类型的协议扩展
在下面的示例中,我正在构建一个处理未知对象类型的协议,我只知道该类型可以是Ios Swift:覆盖属性类型的协议扩展,ios,swift,protocols,Ios,Swift,Protocols,在下面的示例中,我正在构建一个处理未知对象类型的协议,我只知道该类型可以是String或Int或完全不同的类Resource。我想通过添加扩展来支持这些不同类型的类。至少我认为正确的方法是: public protocol InstrumentProtocol : class { associatedtype Item: AnyObject var item: Item? { get set } var identifier: String? { get } } pub
String
或Int
或完全不同的类Resource
。我想通过添加扩展来支持这些不同类型的类。至少我认为正确的方法是:
public protocol InstrumentProtocol : class {
associatedtype Item: AnyObject
var item: Item? { get set }
var identifier: String? { get }
}
public class AbstractBase : InstrumentProtocol {
public var item: AnyObject?
public var identifier: String?
public init(_ i : AnyObject) {
item = i
}
public func about() {
print(self.item) // Any Object
}
}
public extension InstrumentProtocol where Self.Item : Instrument {
public func about() {
print(self.item) //Should be of Instrument type
}
}
public extension InstrumentProtocol where Self.Item : String {
public func about() {
print(self.item) //Should be of String type
}
}
这是我想要实现的,但我不可能解决两种类型的项
项
属性类型我不知道。有什么好办法吗 我想我有办法解决你的问题。您可以这样做:
public class AbstractBase<T> {
public var item: T?
public init(_ i : T) {
item = i
}
public func about() {
print("Any")
print(self.item)
}
}
public extension AbstractBase where T == Int {
public func about() {
print("Int")
print(self.item)
}
}
public extension AbstractBase where T == String {
public func about() {
print("String")
print(self.item)
}
}
将在控制台中为您提供:
String
Optional("string")
Int
Optional(4)
任何其他类型都将转到AbstractBase
about()实现
当然,编译器必须在编译时知道类型。如果您需要在运行时识别类型,我认为强制转换是唯一的方法
我希望它能帮助您。没有相应的typealias
的associatedtype
是无用的。如果您知道Item
只能是三种不同的类型,那么最好创建一个符合这三种类型的协议。好的,您仍然需要将类型强制转换为静态类型,但是一切都比AnyObject
好。如果我必须强制转换类型,那么我可以在不为每个类型创建单独协议的情况下进行转换。有没有其他办法?也许没有associatedtype
方法?
String
Optional("string")
Int
Optional(4)