Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

iOS Delegates in Swift 2 Introduction to Delegates Implementing a Delegate

Corey Dutson
PLUS
Corey Dutson
Courses Plus Student 3,193 Points

Structs and AnyObject

I'm going through the delegates videos, and in the last one, there's a point where we pass in Horse() to a function declaration looking for AnyObject. This complains (at least it does with Swift 2.0). I found I had to swap it to Any to get the errors to silence.

Anyone else run into this? Was my solution the correct one?

Alexey Sobolevsky
Alexey Sobolevsky
5,634 Points

Can you present your code, please?

Corey Dutson
Corey Dutson
Courses Plus Student 3,193 Points

Okay so:

protocol RaceDelegate {
    func raceDidEnd(winner: AnyObject) # if I change this to Any, everything's fine
}

class Race {
    var delegate: RaceDelegate?
    func end() {}
}

class HorseRace: Race {
    let participants: [Horse]
    override func end() {
        delegate?.raceDidEnd(Horse()) # error here
        # Argument type 'Horse' does not conform to expected type 'AnyObject'
    }
}

3 Answers

John Ambrose
John Ambrose
7,216 Points

The problem was that code changed between the initial video and this one. Specifically the struct Horse was changed to a class. A Struct is a value type, and a Class is a reference type. So these are not the same things. AnyObject is meant to only refer to "classes" which if you option click AnyObject, you'll see is the description.

If you update your participants to classes (which if you scrub through the video is what Pasan did) your error will go away since you'll have a compatible type for AnyObject.

For all that are encountering this now, this is a Swift version issue. "AnyObject" has been changed to any.

Change these lines of code:

    func raceStatus(lapNumber: Int, first: AnyObject)   
    func raceDidEnd(winner: AnyObject)

to this:

    func raceStatus(lapNumber: Int, first: Any)   
    func raceDidEnd(winner: Any)
Alexey Sobolevsky
Alexey Sobolevsky
5,634 Points

Try to replace AnyObject with Horse class. May be it is the Swift different version problem.

protocol RaceDelegate {
    func raceDidEnd(winner: Horse)
}