简体   繁体   English

Swift:为多种类型的变量建模

[英]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. 我希望能够执行Alarm.sound.title之类的功能,并让标题返回,而不管它是歌曲,艺术家还是播放列表。 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. 由于您想使用Swift,因此建议您使用协议。 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: 然后,您可以简单地访问任何符合Sound协议的对象的title

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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