Skip to content

Instantly share code, notes, and snippets.

@nvkiet
Last active April 23, 2016 20:36
Show Gist options
  • Select an option

  • Save nvkiet/4a6c5ed7f999a4101356 to your computer and use it in GitHub Desktop.

Select an option

Save nvkiet/4a6c5ed7f999a4101356 to your computer and use it in GitHub Desktop.
Declare a static variable in a function
class func countryNames() -> [String] {
struct Static {
static var instance: [String]?
}
if let names = Static.instance {
return names
}
var names = [String]()
for code in NSLocale.ISOCountryCodes() as [String] {
let identifier = NSLocale.localeIdentifierFromComponents([NSLocaleCountryCode: code])
let name = NSLocale.currentLocale().displayNameForKey(NSLocaleIdentifier, value: identifier)
if name != nil {
names.append(name)
}
}
Static.instance = names.sorted{ (name1: String, name2: String) -> Bool in
switch name1.localizedCaseInsensitiveCompare(name2) {
case .OrderedAscending: return true
default: return false
}
}
return Static.instance!
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment