2

Considering a Swift Object class Sheep having a simple property var position: CGRect

class Sheep {
    var position: CGRect

    init() {
        position = CGRectZero
    }
}  

In an array of Sheep Array<Sheep> How can I get the Sheep with the highest position.origin.y?

I tried the following but got an 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)}
}

All classes import

import Foundation
import QuartzCore

1 Answer 1

2

max is going to return a CGFloat (whichever y is greater). Instead you want to return the sheep that has the highest y value:

return sheeps.reduce(sheeps[0]) {
    ($0.position.origin.y > $1.position.origin.y) ? $0 : $1
}

But be careful because this method will throw a runtime error if sheeps is nil. I would make the return value optional and do the following:

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
    }
}

You need to setup initial as a separate variable to massage the generic in reduce to be correct.

Sign up to request clarification or add additional context in comments.

7 Comments

i get however the error: Type '($T14, $T18)' does not conform to protocol 'LogicValue'
@NicolasManzini are you sure you copied exactly? I ran this code in a playground just fine
indeed NO :) i didn't copy exactly I made a mistake somewhere
@NicolasManzini Also be careful that this function will throw a runtime error if sheeps does not contain at least one sheep
yes i was trying to figure out how I could nil the default parameter and return a Sheep? var
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.