swift - 将运算符重载为通用函数

标签 swift generics

我在“Pro swift”一书中看到了一个例子。

它重载了运算符,第一个参数“lhs”是一个接受 T -> U 的函数。

但是“generateRandomNumber”函数是 Int -> Int

它如何在 >>> 运算符上工作?

它是如何工作的?

谢谢。

import Foundation
infix operator >>> { associativity left }
func >>> <T, U, V>(lhs: T -> U, rhs: U -> V) -> T -> V { 
    return { rhs(lhs($0)) }
}

func generateRandomNumber(max: Int) -> Int {
    let number = Int(arc4random_uniform(UInt32(max)))
    print("Using number: \(number)")
    return number
}
func calculateFactors(number: Int) -> [Int] {
    return (1...number).filter { number % $0 == 0 }
}
func reduceToString(numbers: [Int]) -> String {
    return numbers.reduce("Factors: ") { $0 + String($1) + " " }
}

let combined = generateRandomNumber >>> calculateFactors >>>
reduceToString
print(combined(100))

最佳答案

请参阅有关泛型的文档。

let combined = generateRandomNumber >>> calculateFactors >>> reduceToString
print(generateRandomNumber.dynamicType)
print(calculateFactors.dynamicType)
print(reduceToString.dynamicType)
print(combined.dynamicType)
/*
 Int -> Int
 Int -> Array<Int>
 Array<Int> -> String
 Int -> String
 */

关于swift - 将运算符重载为通用函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38167349/

相关文章:

java - 类型删除如何在 Java 中用于通配符?

java - 有什么用?在 java

带有未从类导出参数的 JavaScriptCore 方法

ios - 在 UICollectionView (SWIFT) 中设置默认单元格?

ios - interactivePopGestureRecognizer 弹出到根而不是 1 个顶部 Controller

ios - 自动布局 : frame is 600x480 in compact/Any size class, 的 ScrollView 大小大于 iphone5?

ios - 在 SwiftUI 中更改 slider 拇指

json - 如何在 Dart 中使用带有 json 序列化的泛型和泛型列表?

swift - 实现通用协议(protocol)编译器错误

c# - 使用正确的派生类型调用泛型方法