过载运算符作为泛型函数

时间:2016-07-03 06:31:51

标签: swift generics

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

它使运算符重载,第一个参数“lhs”是一个取T - >的函数。 Ú

但“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))

1 个答案:

答案 0 :(得分:1)

请参阅有关泛型的文档。

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
 */