[英]How can i pass class as a parameter to a function in Swift?
讓我們考慮一下我有兩個不同的班級。
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幫助我實現這一目標
您不能在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
}
}
使用協議
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))
輸出:
你好
世界
創建A和B都符合的協議,並將其用作update()中的參數類型
protocol SomeProtocol {
var something: String {get set}
}
func update(_ o: SomeProtocol) {
print(o.something)
}
眾所周知,我認為使用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
可能會更整潔- 參考
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")
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.