【问题标题】:Swift - is there a standard protocol that defines +,-,*,/ functions, which is adopted by all "arithmetic" types like Double, Float, Int etc.? [duplicate]Swift - 是否有定义 +、-、*、/ 函数的标准协议,所有“算术”类型(如 Double、Float、Int 等)都采用该协议? [复制]
【发布时间】:2015-07-09 18:03:34
【问题描述】:

我想编写一个通用函数,它将返回它的两个参数之和,如下所示:

func add<T: ???>(left: T, right: T) -> T {
    return left+right
}

当然,为了使用+运算符,T类型需要符合定义+运算符的协议。

如果是其他几个运算符,则有内置协议 - 例如Equatable 用于==,Comparable 用于&lt;、&gt; 等。这些协议被所有 Swift 内置的“算术”类型所采用,例如 Double、Float、Int16 等。

是否有定义+、-、*、/ 运算符的标准协议,它被所有“算术”类型(如 Double、Float、Int、UInt、Int16 等)采用?

【问题讨论】:

  • 你正在做的正是如何去做。目前尚不清楚您要寻找什么答案;你的问题不是真正的问题,更像是一个呻吟......
  • 为什么Double 应该符合IntegerArithmeticType? Double 可以表示不是 Integer 的东西。
  • 您能否改进或删除这个问题? -> stackoverflow.com/help/how-to-ask
  • 题主有什么问题?他在问是否有更好的方法。
  • 好的,我重写了这个问题,让它更清楚。

标签: swift generics swift2


【解决方案1】:

图书馆里没有任何东西,我明白你的意思。不过你可以自己做:

protocol Arithmetic {
    func +(lhs: Self, rhs: Self) -> Self
    func -(lhs: Self, rhs: Self) -> Self
    func *(lhs: Self, rhs: Self) -> Self
    func /(lhs: Self, rhs: Self) -> Self
}

extension Int8 : Arithmetic {}
extension Int16 : Arithmetic {}
extension Int32 : Arithmetic {}
extension Int64 : Arithmetic {}

extension UInt8 : Arithmetic {}
extension UInt16 : Arithmetic {}
extension UInt32 : Arithmetic {}
extension UInt64 : Arithmetic {}

extension Float80 : Arithmetic {}
extension Float : Arithmetic {}
extension Double : Arithmetic {}


func add<T: Arithmetic>(a: T, b: T) -> T {
    return a + b
}

add(3, b: 4)

【讨论】:

  • 是的,我已经写了完全相同的东西 :) 但是,在我看来,这是真正应该包含在标准库中的东西之一。尤其是当 Apple 喜欢称 Swift 为 面向协议的编程语言 ;)
  • Apple 听了,并且有一个协议:“数字”。见developer.apple.com/documentation/swift/numeric
  • @KarolyNyisztor 数字不支持除法
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-10-13
  • 2017-10-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多