Home > Enterprise >  How can I define label for items of a struct in Swift?
How can I define label for items of a struct in Swift?

Time:08-02

This is my struct:

struct TestType {
    var name: String
    var age: Int
}

I am looking to define a label for items inside this struct, almost like a label to give needed info about the item, like we can do for enums like this:

enum TestEnum {

    case name(String)
    case age(Int)
    
    var label: String {
        switch self {
        case .name:
            return "Name of person"
        case .age:
            return "Age of person"
        }
    }
    
    var value: Any {
        switch self {
        case .name(let string):
            return string
        case .age(let int):
            return int
        }
    }
}

So my goal is working on struct for defining a label kind computed property, like this:

let value: TestType = TestType(name: "Bob", age: 25)

let newValue1: String = value.name.label  // It should gave: "Name of person"
let newValue2: String = value.age.label   // It should gave: "Age of person"

How can I do this?

My idea is simply using tuple instead of String or Int like (String, String) or (Int, String)

CodePudding user response:

A possible solution would be to not declare directly name & age as String/Int, but as a intermediary struct which can hold the label and the value:

struct Label<T> {
    var value: T
    var label: String
}

Then, you can have:

struct TestType {
    var name: Label<String>
    var age: Label<Int>

    init(name: String, age: Int) {
        self.name = Label(value: name, label: "Name of person")
        self.age = Label(value: age, label: "Age of person")
    }
}

And in use:

let test = TestType(name: "Bob", age: 25)
let nameValue = test.name.value
let nameLabel = test.name.label
let ageValue = test.age.value
let ageLabel = test.age.label
print(nameValue)
print(nameLabel)
print(ageValue)
print(ageLabel)

Output:

$>Bob
$>Name of person
$>25
$>Age of person
  • Related