progammingBeignner
progammingBeignner

Reputation: 936

A better way to do Language in swift 3

i am currently doing an app that has language change feature. However,for every string that i wish to have changes made to when a different language is selected, i have to implement the following code

"Hello world".localize()

However, as the app gets bigger, the code become very messy in the way that all the strings in their respective view controllers have this .localize() append to it.

Is there a way where i can do this .localize() thing in one central place?

EDIT: I tried to create a Strings.swift file and put all the strings inside. I did something like this.

static let relevantString = "hello world".localize()

and then in the view controllers i call

let myString = relevantString 

However, this does not well. The strings will only change after i terminate the app and restart it.

Upvotes: 0

Views: 113

Answers (1)

CRD
CRD

Reputation: 53010

Your attempt to use static let fails to produce the dynamic behaviour you want simply because you used a constant. You could use a read only computed property instead, something like:

var relevantString : String { return "Hello World".localize() }

As an alternative, as you seem to be more concerned over the clutter, you could define a simple prefix or postfix unary operator which called localize() on its argument. Swift allows a number of symbols to be used as operators so the operator can just be a single character. For example you could define, say, § so that §"Hello World" produced a localised string.

HTH

Upvotes: 2

Related Questions