gpt4 book ai didi

swift - 避免 switch 支持没有类的多态性

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

我正在寻找一种方法来使函数接受特定的 switch case,或者任何其他方法来实现我想要的,就像这样:

protocol CommonType {}
struct A: CommonType {}
struct B: CommonType {}

func f(_ a: A) {
print("A")
}
func f(_ b: B) {
print("B")
}

let x: CommonType = A()
f(x) // expect to print "A"

所以基本上我需要一种方法来根据我的结构类型有条件地调用 f

显然我可以这样做:

switch x {
case let y as A:
f(y)
case let y as B:
f(y)
default: ()
}

但这正是我想要避免的(即,我正在寻找一种更优雅的方式)。

最佳答案

多态性适用于类、结构和枚举的方法。具有独立函数的多态性没有意义。您定义的是重载函数。

如何将函数添加到您的协议(protocol)定义中?这样,编译器将确保实现 CommonType 的每个 classstructenum 都将实现 函数f():

protocol CommonType {
func f()
}
struct A: CommonType {
func f() {
print("A")
}
}
struct B: CommonType {
func f() {
print("B")
}
}

let x: CommonType = A()
x.f() // prints "A"

Nope, I need it as a function, because I'll use those in multiple places that are totally unrelated, so my protocol would be bloated. Plus, I'm more into FP than OO.

我不明白对臃肿协议(protocol)的担忧。通过将函数添加到协议(protocol)定义中,您可以确保每个实现该协议(protocol)的结构都能正确实现它。编译器将强制执行它。如果你坚持一个函数,你可以写一个包装器:

func f(_ x: CommonType) {
x.f()
}

f(x) // prints "A"

关于swift - 避免 switch 支持没有类的多态性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46415531/

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