我是Swift的新手,现在正在玩子类化。我要实现的目标是通过子类化将存储的属性简单地添加到现有类中,然后将现有实例从该类复制到子类中。我正在尝试使用MPMediaEntity并以这种方式将其子类化:
class MPMediaEntityWithMyString: MPMediaEntity{
var myString:String = ""
}
然后,要获取MPMediaEntities列表,只需执行以下操作:
// Get all the songs in an array
let mediaItems = MPMediaQuery.songsQuery().items
// Go through each song, make a copy of it as MPMediaEntityWithMyString
// and modify the myString property
for song in mediaItems{
// This is where I stall. How do I copy the MPMediaEntity into the MPMediaEntityWithMyString? It moans about it not being convertible
var songCopy:MPMediaEntityWithMyString = song
songCopy.myString = "testing!"
println(songCopy.myString)
}
我在做什么,这显然是错误的?
在不了解整个项目的情况下,我建议您使用组合而不是继承。这意味着您将创建一个类,该类(或者可能更适合使用struct)具有一个属性,MPMediaEntity
并且具有另一个type属性String
。
这有效地将您的自定义数据对象与任何其他类的混乱继承树分离。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句