Loris Loris - 21 days ago 13
Swift Question

Swift Eureka Forms - How to assign values to field options?

If I create a segmented row field like so:

<<< SegmentedRow<String>(){ row in
row.title = "Sex"
row.tag = "sex"
row.selectorTitle = "Select your sex"
row.options = ["Male","Female"]
}


How do I match the options to a specific value? For example if a user select Male, then is there a way to get
M
instead of
Male
in code, but still shows
Male
to the User?

Or if I have a list of countries for example:

<<< PushRow<String>(){ row in
row.title = "Passport Issuing Country"
row.tag = "passportIssuingCountry"
row.selectorTitle = "Passport Issuing Country"
row.options = ["AUSTRALIA","AUSTRIA","BELGIUM"]
}


can I assign each Country name to a country code, like
AUSTRALIA
will return
AU
,
AUSTRIA
will return
AT
, etc.

Answer

Right now, there's no way to hold an internal value for an option - but this is what you can do:

1. Create an enum with all available options

enum Sex: Int {
    case NotKnown       = 0
    case Male           = 1
    case Female         = 2
    case NotApplicable  = 9

    static let all      = [NotKnown, Male, Female, NotApplicable]
    static let strings  = ["Unknown", "Male", "Female", "Not Applicable"]

    func string() -> String {
        let index = Sex.all.index(of: self) ?? 0
        return Sex.strings[index]
    }

    static func fromString(string: String) -> Sex {
        if let index = Sex.strings.index(of: string) {
            return Sex.all[index]
        }
        return Sex.NotKnown
    }
}

2. Create your row with all the options you want to expose

<<< SegmentedRow<String>(){ row in
    row.title = "Sex"
    row.tag = "sex"
    row.selectorTitle = "Select your sex"
    row.options = [Sex.Female.string(), Sex.Male.string()]
}

3. Read the value

let row: SegmentedRow<String>? = self.form.rowBy(tag: "sex")
if let value = row?.value {
    // Returns "Female"
    print(value)

    // Returns 2
    print(Sex.fromString(string: value).rawValue)
}

The user sees and selects Strings, but you get an enum-value that you for example can save in your database as an integer (see: ISO/IEC 5218).

https://en.wikipedia.org/wiki/ISO/IEC_5218

Comments