让我们考虑一下我有两个不同的班级。
class A {
var something = "Hello"
}
class B {
var something = "World"
}
现在
class C {
func request() {
//Call with class A or B it can contain any class. I can call either class A or B depending on condition
update(myClass: A or B)
}
func update(myClass:A or B ) {
print(myClass.something) //Since both class have same varaible var something so this code should work either i pass class A or B through function
}
}
请帮助我使用Swift
答案 0 :(得分:6)
您不能在Swift中声明一个可以接受几种不同类型的输入参数的函数,因此您不能将类型声明为A or B
。但是,您实际上并不需要用它来解决您的特定问题。
由于要访问两个类实例的公共属性,因此应在协议中声明该属性,使两个类均符合该协议,然后使该函数采用协议类型的输入参数。
protocol SomethingProtocol {
var something: String { get }
}
class A: SomethingProtocol {
let something = "Hello"
}
class B: SomethingProtocol {
let something = "World"
}
class C {
func request() {
//Call with class A or B it can contain any class. I can call either class A or B depending on condition
update(something: A())
update(something: B())
}
func update(something: SomethingProtocol) {
print(something.something) //Since both class have same varaible var something so this code should work either i pass class A or B through function
}
}
答案 1 :(得分:4)
使用协议
protocol MyProtocol: class {
var something: String { get set }
}
class A: MyProtocol {
var something = "Hello"
}
class B: MyProtocol {
var something = "world"
}
class C {
func update(myClass:MyProtocol ) {
print(myClass.something) //Since both class have same varaible var something so this code should work either i pass class A or B through function
}
}
用法:
let a = A()
let b = B()
let c = C()
print(c.update(myClass: a))
print(c.update(myClass: b))
输出:
你好
世界
答案 2 :(得分:2)
创建一个A和B都符合的协议,并将其用作update()中的参数类型
protocol SomeProtocol {
var something: String {get set}
}
func update(_ o: SomeProtocol) {
print(o.something)
}
答案 3 :(得分:0)
众所周知,我认为使用protocol
是最能解决您问题的最干净的方法。
但是,可以使用Any
作为参数传递任何对象,这将需要检查您在update方法内部处理的是哪个类。
像这样...
class C {
func update(myClass: Any) {
if let a = myClass as? A {
print(a.something)
}
if let b = myClass as? B {
print(b.something)
}
}
}
这可能更适合switch
-ref
class C {
func update(myClass: Any) {
switch myClass {
case let a as A:
print(a.something)
case let b as B:
print(b.something)
default:
print("not a thing")
}
}
}