One of the great things about Swift for iOS / tvOS development is how the language can be extended.
Here are some useful string extensions for Swift:
extension String {
var length : Int {
return self.characters.count
}
subscript(integerIndex: Int) -> Character {
let index = startIndex.advancedBy(integerIndex)
return self[index]
}
subscript(integerRange: Range<Int>) -> String {
let start = startIndex.advancedBy(integerRange.startIndex)
let end = startIndex.advancedBy(integerRange.endIndex)
let range = start..<end
return self[range]
}
var localized: String {
return NSLocalizedString(self, tableName: nil, bundle: NSBundle.mainBundle(), value: "", comment: "")
}
}
Add this code to a file such as StringExtension.swift
and you're good to go.
String Length
As its name implies, you can determine the length of a string in a much simpler way:
let myStr = "Hello"
print("The string \(myStr) has \(myStr.length) characters")
Single Character
You can retrieve a single character from a string using an integer subscript:
let myStr = "Hello"
let first = myStr[0]
print("The first character of \(myStr) is \(first)")
Substring
You can retrieve a substring using an integer range:
let myStr = "Goodbye"
let good = myStr[0 ... 3]
let bye = myStr[4 ..< 7]
Localised String
It's best practice to not hard-code any string that is displayed in your code. Instead, strings should be kept in a strings file (such as Localizable.strings
, of which there would be one such file for each translated language).
A single entry in the strings file may look as follows:
"HelloMessage" = "Hello";
Using the .localized
extension above, you can bring in the translated string as follows:
let translatedHello = "HelloMessage".localized
print("The translated version is \(translatedHello)")
Do you have any other useful string extensions? Email us: hello@crunchybagel.com.