gpt4 book ai didi

swift - 如何将类作为参数传递给 Swift 中的函数?

转载 作者:搜寻专家 更新时间:2023-11-01 05:46:11 26 4
gpt4 key购买 nike

让我们考虑一下我有两个不同的类(class)。

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 或 B。但是,您实际上并不需要它来解决您的特定问题。

既然你想访问两个类实例的公共(public)属性,你应该在协议(protocol)中声明该属性,使两个类都符合该协议(protocol),然后让函数接受协议(protocol)类型的输入参数。

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
}

}

关于swift - 如何将类作为参数传递给 Swift 中的函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54929066/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com