考虑 Swift 对象 class Sheep
拥有一个简单的属性var position: CGRect
class Sheep {
var position: CGRect
init() {
position = CGRectZero
}
}
在绵羊数组中 Array<Sheep>
我怎样才能得到Sheep
最高position.origin.y
?
我尝试了以下操作,但得到了 error: could not find member y
func firstSheep(sheeps: Array<Sheep>) -> Sheep
{
return sheeps.reduce(sheeps[0]) {max($0.position.origin.y, $1.position.origin.y)}
}
导入所有类
import Foundation
import QuartzCore
最佳答案
max
将返回 CGFloat(以 y 较大者为准)。相反,您想要返回具有最高 y 值的羊:
return sheeps.reduce(sheeps[0]) {
($0.position.origin.y > $1.position.origin.y) ? $0 : $1
}
但要小心,因为如果 sheeps
为零,此方法将引发运行时错误。我将使返回值可选并执行以下操作:
func firstSheep(sheeps: [Sheep]) -> Sheep?
{
let initial : Sheep? = nil
return sheeps.reduce(initial) {
if !$0 {
return $1
}
return ($0!.position.origin.y > $1.position.origin.y) ? $0 : $1
}
}
您需要将初始设置为单独的变量,以保证 reduce
中的泛型正确。
关于functional-programming - 如何在 Swift 中对自定义对象数组使用reduce函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24234763/