I am new to Swift and playing with subclassing at the moment. What I am trying to achieve is to simply add a stored property to an existing class by subclassing it, then making a copy of an existing instance from the class into the subclass. I'm trying this with MPMediaEntity and have subclassed it this way:
class MPMediaEntityWithMyString: MPMediaEntity{
var myString:String = ""
}
Then to get a list of MPMediaEntities I simply do:
// 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)
}
What am I doing which is obviously wrong?
Without knowing your entire project, I would suggest using composition instead of inheritance. That would mean you create a class (or maybe a struct is more appropriate) that has a property of the MPMediaEntity
and another property of type String
.
This effectively decouples your custom data object from the messy inheritance tree of any other class.