mercredi 19 avril 2017

How to reduce code duplication for class properties (Swift 3)

In my application I want to implement separate class to keep all the temporary variables of Now Playing item for Music Player. It has lots of properties with different types, but they should be handled in the same way.

This is my code:

struct DataDefaults {
    //MARK: Default properties
    let albumTitle: String? = "Unknown Album"
    let albumArtist: String? = "Unknown Artist"
    let title: String? = "Unknown Title"
    let artist: String? = "Unknown Artist"
    let artwork: UIImage? = UIImage(named: "noartwork")!
    let genre: String? = ""
    let lyrics: String? = "No Lyrics"
    let releaseDate: Date? = nil
    let playbackDuration: TimeInterval? = 0
    let rating: Int? = 0
    let assetURL: URL? = nil
    let isExplicitItem: Bool? = false
    let isCloudItem: Bool? = false
    let hasProtectedAsset: Bool? = false
}

class SongInfo: NSObject {

    static let sharedData = SongInfo()

    let defaults = DataDefaults()

    //MARK: Properties
    var albumTitle: String
    var albumArtist: String
    var title: String
    var artist: String
    var artwork: UIImage
    var genre: String
    var lyrics: String
    var releaseDate: Date?
    var playbackDuration: TimeInterval
    var rating: Int
    var assetURL: URL?
    var isExplicitItem: Bool
    var isCloudItem: Bool
    var hasProtectedAsset: Bool


    //MARK: Init
    private override init () {
        self.albumTitle = defaults.albumTitle!
        self.albumArtist = defaults.albumArtist!
        self.title = defaults.title!
        self.artist = defaults.artist!
        self.artwork = defaults.artwork!
        self.genre = defaults.genre!
        self.lyrics = defaults.lyrics!
        self.releaseDate = defaults.releaseDate
        self.playbackDuration = defaults.playbackDuration!
        self.rating = defaults.rating!
        self.assetURL = defaults.assetURL
        self.isExplicitItem = defaults.isExplicitItem!
        self.isCloudItem = defaults.isCloudItem!
        self.hasProtectedAsset = defaults.hasProtectedAsset!
    }

    //MARK: Set properties
    func updateData(allData: DataDefaults) {
        var wasUpdated: Bool = false

        if allData.albumTitle == self.albumTitle {
            //pass
        } else if allData.albumTitle == nil || allData.albumTitle == "" {
            self.albumTitle = defaults.albumTitle!
            wasUpdated = true
        } else {
            self.albumTitle = allData.albumTitle!
            wasUpdated = true
        }

        //Need to repeat same IF for all properties
    }
}

Is there any way I can use property name to make some reusage of the same code instead of duplicating it?






Comments
0 Comments

0 commentaires:

Enregistrer un commentaire