简体   繁体   中英

Swift: Modeling a variable with multiple types

I'm building an alarm app where each alarm has a sound associated with it.

The sound can either be a song, artist([song]), or playlist([song]); all of which have a title and other specific properties.

I'd like to be able to do things like alarm.sound.title and have the title return regardless of if it's a song, artist, or playlist. I also need to implement logic where the app behaves differently depending on whether it's a song, artist, or playlist.

I'm not sure if I should be creating a sound class with a type property and subclasses song, artist, playlist or if there is a better way to structure the data. I read about typecasting but I'm not sure if that's the right direction.

Any advice on how to model this would be appreciated. Thanks

Since you want to use Swift I'd suggest using protocols. That would give what you need. Simple example:

protocol Sound {
    let title: String { get }
    let length: TimeInterval { get }
}

The protocol would define the interface. Then you can just create various classes which would conform to the protocol - the underlaying implementation can be completely different:

class Song: Sound {
    var title: String
    var length: TimeInterval

    init(title: String, length: TimeInterval) {
        self.title = title
        self.length = length
    }
}

class Artist: Sound {
    var title: String {
        return "Artist"
    }
    var length: TimeInterval {
        return 11.1
    }
}

Then you can simply access title on any object conforming to the Sound protocol:

let sound1: Sound = Song(title: "Song", length: 1)
let sound2: Sound = Artist()

print("\(sound1.title)")  // prints: Song
print("\(sound2.title)")  // prints: Artist

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM