gpt4 book ai didi

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

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

我在“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/

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