Heruhaundo
Heruhaundo

Reputation: 21

Strings Dictionary with dynamic units

I would like to dynamically specify the unit to be used (e.g. hours, minutes, seconds) in the Strings Dictionary when called:

Text("\(unit) \(value))", tableName: "SingularAndPlural")

Strings Dictionary

But that doesn't work, it doesn't resolve.

I've tried all possible variants, but I can't get any further.

Upvotes: 2

Views: 94

Answers (1)

Ashley Mills
Ashley Mills

Reputation: 53161

Rather than use stringsDict you should probably use localisation provided by the built-in Formatters. In this case DateComponentsFormatter probably does what you need:

struct ContentView: View {
    
    var body: some View {
        List {
            ForEach(["en", "ru", "el", "th"], id: \.self) { localeId in
                Section(localeId) {
                    ForEach(0..<3, id: \.self) { i in
                        HStack {
                            Text(formatter(localeId).string(from: DateComponents(minute: i))!)
                            Spacer()
                            Text(formatter(localeId).string(from: DateComponents(second: i))!)
                        }
                    }
                }
            }
        }
    }
            
    func formatter(_ localeId: String) -> DateComponentsFormatter {
        var calendar = Calendar.current
        calendar.locale = Locale(identifier: localeId)
        let formatter = DateComponentsFormatter()
        formatter.calendar = calendar
        formatter.unitsStyle = .full
        return formatter
    }
}

enter image description here

It's even simpler if you just want to format for the device's current locale:

struct ContentView: View {
    
    var body: some View {
        List {
            ForEach(0..<3, id: \.self) { i in
                HStack {
                    Text(DateComponents(minute: i), formatter: Self.formatter)
                    Spacer()
                    Text(DateComponents(second: i), formatter: Self.formatter)
                }
            }
        }
    }
    
    static var formatter: DateComponentsFormatter {
        let formatter = DateComponentsFormatter()
        formatter.unitsStyle = .full
        return formatter
    }
}

Upvotes: 1

Related Questions