Amit Erandole
Amit Erandole

Reputation: 12281

Why is my simple swift delegate and protocol setup not working?

I am trying to grasp the concept of delegates and protocols in swift. So I have implemented my own PlayableMedia protocol with two concrete classes BlueRayMedia and DVDMedia like so:

@protocol PlayableMedia {
    func play()
    func stop()
}

class BlueRayMedia:PlayableMedia {

    func play() {
        println("BlueRayMedia is playing")
    }

    func stop() {
        println("BlueRayMedia has stopped playing")
    }

}

class DVDMedia:PlayableMedia {

    func play() {
        println("DVD is playing")
    }

    func stop() {
        println("DVD has stopped playing")
    }


}

So now I have a DVDPlayer class that uses this setup:

class DVDPlayer {

    var media:PlayableMedia // delegate property

    init(media:PlayableMedia){
        self.media = media
    }

    func didStartPlaying() {
       media.play()
    }

    func didStopPlaying() {
        media.stop()
    }

}

But when I try to use it like this:

var dvdPlayer:DVDPlayer = DVDPlayer(media: BlueRayMedia())

dvdPlayer.didStartPlaying()

I get (no results) in my playground console. What am I doing wrong?

Upvotes: 3

Views: 1540

Answers (2)

Amit Erandole
Amit Erandole

Reputation: 12281

Ok so the simple mistake I made was use @protocol instead of just protocol

So this works:

protocol PlayableMedia {
    func play()
    func stop()
}

Upvotes: 2

Loganathan
Loganathan

Reputation: 1787

Inside the Playground println() doesn't work. Add some other expression like let x = 5

Upvotes: 0

Related Questions