Type 应该采用什么协议来让泛型函数将任何数字类型作为 Swift 中的参数?

What protocol should be adopted by a Type for a generic function to take any number type as an argument in Swift?(Type 应该采用什么协议来让泛型函数将任何数字类型作为 Swift 中的参数?)
本文介绍了Type 应该采用什么协议来让泛型函数将任何数字类型作为 Swift 中的参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

我想让一个函数在 Swift 中接受任何数字(Int、Float、Double、...)

I want to make a function accept any number (Int, Float, Double, ...) in Swift

func myFunction <T : "What to put here"> (number : T) ->  {
    //...
}

不使用 NSNumber

without using NSNumber

推荐答案

更新: 下面的答案原则上仍然适用,但是 Swift 4 完成了对数字协议的重新设计,以便添加您自己的通常是不必要的.在构建自己的系统之前,请查看标准库的数字协议.

Update: The answer below still applies in principle, but Swift 4 completed a redesign of the numeric protocols, such that adding your own is often unnecessary. Take a look at the standard library's numeric protocols before you build your own system.

这实际上在 Swift 中是不可能开箱即用的.为此,您需要创建一个新协议,使用您将在泛型函数中使用的任何方法和运算符进行声明.此过程对您有用,但具体细节将在一定程度上取决于您的通用函数的作用.以下是获取数字 n 并返回 (n - 1)^2 的函数的方法.

This actually isn't possible out of the box in Swift. To do this you'll need to create a new protocol, declared with whatever methods and operators you're going to use inside your generic function. This process will work for you, but the exact details will depend a little on what your generic function does. Here's how you'd do it for a function that gets a number n and returns (n - 1)^2.

首先,定义您的协议,使用运算符和一个采用 Int 的初始化程序(这样我们就可以减去一个).

First, define your protocol, with the operators and an initializer that takes an Int (that's so we can subtract one).

protocol NumericType {
    func +(lhs: Self, rhs: Self) -> Self
    func -(lhs: Self, rhs: Self) -> Self
    func *(lhs: Self, rhs: Self) -> Self
    func /(lhs: Self, rhs: Self) -> Self
    func %(lhs: Self, rhs: Self) -> Self
    init(_ v: Int)
}

所有数字类型已经实现了这些,但此时编译器并不知道它们是否符合新的NumericType 协议.你必须明确这一点——Apple 称之为通过扩展声明采用协议".我们将为 DoubleFloat 和所有整数类型执行此操作:

All of the numeric types already implement these, but at this point the compiler doesn't know that they conform to the new NumericType protocol. You have to make this explicit -- Apple calls this "declaring protocol adoption with an extension." We'll do this for Double, Float, and all the integer types:

extension Double : NumericType { }
extension Float  : NumericType { }
extension Int    : NumericType { }
extension Int8   : NumericType { }
extension Int16  : NumericType { }
extension Int32  : NumericType { }
extension Int64  : NumericType { }
extension UInt   : NumericType { }
extension UInt8  : NumericType { }
extension UInt16 : NumericType { }
extension UInt32 : NumericType { }
extension UInt64 : NumericType { }

现在我们可以编写我们的实际函数,使用 NumericType 协议作为通用约束.

Now we can write our actual function, using the NumericType protocol as a generic constraint.

func minusOneSquared<T : NumericType> (number : T) -> T {
    let minusOne = number - T(1)
    return minusOne * minusOne
}

minusOneSquared(5)              // 16
minusOneSquared(2.3)            // 1.69
minusOneSquared(2 as UInt64)    // 1

这篇关于Type 应该采用什么协议来让泛型函数将任何数字类型作为 Swift 中的参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

Stub value of Build.VERSION.SDK_INT in Local Unit Test(本地单元测试中 Build.VERSION.SDK_INT 的存根值)
TextWatcher for more than one EditText(TextWatcher 用于多个 EditText)
Find the CGPoint on a UIView rectangle intersected by a straight line at a given angle from the center point(在与中心点成给定角度的直线相交的 UIView 矩形上找到 CGPoint)
Which is the best way to estimate measure of photographed things?(哪种方法是估计拍摄物体尺寸的最佳方法?)
Convert Character to Int in Swift 2.0(在 Swift 2.0 中将字符转换为 Int)
Edit Text shows exception Invalid Int quot;quot;(编辑文本显示异常 Invalid Int “;)