Parth Adroja Parth Adroja - 5 days ago 5
iOS Question

Get and Set different data types in Swift

I am using ObjectMapper. And I know we can specify the keypath like map["name.label"] but I don't want to use keyPath at a moment. Check the below code. I can access name like

Author.name?.label
.

class Author: Mappable {
var name: LabelDict?

required init?(map: Map) {
}

func mapping(map: Map) {
name <- map["name"]
}
}

class LabelDict: Mappable {
var label: String?

required init?(map: Map) {
}

func mapping(map: Map) {
label <- map["label"]
}
}


How can I set the getter and setter methods of the name property of Author class to set the value as
LabelDict
class label and when I get the value I get the
String
directly as
Author.name
. I can do it by using one different variable but is it possible to do with the same?

Answer

You could make your LabelDict adopt CustomStringConvertible protocol.

class LabelDict: Mappable, CustomStringConvertible {
    var label: String?
    var description: String {
        get {
            return self.label ?? ""
        }
    }

    required init?(map: Map) {
    }

    func mapping(map: Map) {
        label <- map["label"]
    }
}

Then you'd use it like this String(describing: myLabelDictInstance).

-- Clarification
To simply print the label into console you can now use print(Author?.name). If you want to assign it to label for example, you can use someLabel.text = String(describing: Author?.name)

Comments