gpt4 book ai didi

swift - 通用加法函数 Swift

转载 作者:行者123 更新时间:2023-11-28 11:10:26 25 4
gpt4 key购买 nike

我想创建一个函数,它可以接受两个参数,并根据输入的类型执行二元运算(例如,“int”简单加法,对于字符串,它应该连接等)并返回结果。对于以下方法,我收到类似“二元运算符‘+’不能应用于两个‘T’操作数”的错误

func commonAdd <T>(paramA:T,paramB:T)->T

最佳答案

一种可能的方法。

1) 可添加协议(protocol)

您定义一个Addable 协议(protocol)。

protocol Addable {
func add(other:Self) -> Self
}

2) commonAdd 函数

接下来你以这种方式定义你的功能

func commonAdd <T: Addable>(paramA:T,paramB:T) -> T {
return paramA.add(paramB)
}

3) 使 Int 符合 Addable

接下来选择一个类型并使其符合Addable

extension Int: Addable {
func add(other: Int) -> Int {
return self + other
}
}

4) 用法

现在您可以将您的函数与 Int 一起使用。

commonAdd(1, paramB: 2) // 3

更多

您应该重复第 3 步,使您希望在函数中使用的每个类型都成为 Addable

关于swift - 通用加法函数 Swift,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35429007/

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