简体   繁体   中英

Swift - copy an MPMediaEntity instance into a subclass

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?

You can not. The BaseClass reference can have Subclass refrence but you can not assign refrence of BaseClass in SubClass.Subclass has some additional properties and behaviours so you cannot assign BaseClass refrence to SubClass.You have to do

let mediaItems = MPMediaEntityWithMyString.songsQuery().items

but these items should be type of MPMediaEntityWithMyString not MPMediaQuery .

One other option is you can use composition instead of inheritance

class MPMediaEntityWithMyString {
    var mediaItem:String?
    var myString:String = ""
}

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.

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