Marmelador
Marmelador

Reputation: 1017

Change class property when set

I have the following class:

class Message {
    var content: [String]?

    init(content: [String]) {
        self.content = content
    }
}

I want content to be an array of Strings, that are always uppercase. Even when lowercase text is set to content. I don't seem to be able to use computed properties for this

Upvotes: 0

Views: 91

Answers (3)

V-Dev
V-Dev

Reputation: 508

init(content: [String]) {

    self.content =  content
    self.setupMyProperty()

 }

 func setupMyProperty() {
        let arrCaps = self.content.map{$0.uppercased()}

       self.content.removeAll() 
      self.content = arrCaps
    }

Upvotes: 0

vacawama
vacawama

Reputation: 154603

You can use a property observer didSet to apply uppercased() to the array when it is set:

class Message {
    var content: [String]? {
        didSet {
            if let arr = content {
                self.content = arr.map { $0.uppercased() }
            }
        }
    }

    init(content: [String]) {
        self.content = content.map { $0.uppercased() }
    }
}

Upvotes: 4

Palle
Palle

Reputation: 12109

You can have an internal variable storing the actual content and a computed property visible to the outside. If the public property is set, it computes the internal (uppercased) representation.

class Message {
    private var _content: [String]?
    var content: [String]? {
        get {
            return _content
        }
        set (new) {
            if let new = new {
                _content = new.map { $0.uppercased() }
            } else {
                _content = nil
            }
        }
    }

    init(content: [String]?) {
        self.content = content
    }
}    

You can even assign content in the initializer and it will compute the upper case representation.

Upvotes: 4

Related Questions