Swift Snippets 1: Strings, Attributed Text, Arrays


Working with Strings.

To append a string to another, try
fullString += extraString
if that is refused, use

Strip leading and trailing white space from a string
let trimmedString = string.trimmingCharacters(in: .whitespaces)

Convert a string to an integer
let theInt = Int(theString)
The snag is that this generates an error if theString contains unconvertible characters. However this is not thrown as an error, so cannot be caught using standard techniques. To make it robust, the string should be pre-parsed.

Convert Int to string (among many ways)
let theStr = String(theInt)

Convert a string to lower case using a mapping
let lowerCase = stringArray.map { $0.lowercaseString }

Replace all occurrences of a string with a string
let newString = aString.replacingOccurrences(of: oldStr, with: newStr)
Replace all occurrences of a character with a character
if (aString != "") {
newString = String(aString.characters.map { $0 == aReg ? aMang : $0 })

compares character referenced as $0 with character aReg, returning aMang if they match
For multiple comparisons of characters
let aReg = Character("a") (etc.)
func encodeChar(inC: Character) -> Character {
if (inC == aReg) { return aMang }
else if (inC == bReg) { return bMang }

else { return inC }
called in a closure
if (aString != "") {
newString = String(aString.characters.map {
return encodeChar(inC: $0)

Divide a string into an array of words which separate at spaces
let theWordArray = string.components(separatedBy: " ")

Obtain the first character of a string, as a string
firstLetter = String(theString[theString.startIndex])

Get the system date and time as a string
let theDate: Date = Date()
theNowStr = theDate.description

Get date and time as separate strings
let theDate: Date = Date()
let theDateStringArray = theDate.description.components(separatedBy: " ")
if (theDateStringArray.count > 1) {
textDate.stringValue = theDateStringArray[0]
textTime.stringValue = theDateStringArray[1]

Set plain text in a text box
textBox.stringValue = theString

Take a plain NSString and insert it as attributed text into a text box
let attr = NSAttributedString(string: theString as String)

to append it, or
let attr = NSAttributedString(string: string as String)

to replace all the existing text with the new text.

For a simple array of strings ["First string", "another", "yet more", "last here"]
theStringList.sort(by: >)
For an array of arrays [["First string", "another", "yet more", "last here"], ["Second string", "This is another", "still more", "last for now"], …]
func forward(_ s1: Array<String>, _ s2: Array<String>) -> Bool {
return s2[1] > s1[1]

called as
theStringList.sort(by: forward)

Count the number of letters in an array of words using a mapping
let counts = stringArray.map { $0.characters.count }

Convert a string to a string of hexadecimal values for each of bytes in UTF-8 encoding
let stringArray = theString.utf8.map { String(format: "%02hhx", $0) }

Collapse an array of strings into a single continuous string
let theString = stringArray.joined(separator: " ")

Parse a string for contents
if theString.contains(aStringFragment) {
} else if theString.contains(anotherStringFragment) { …

Normalise a string using one of the Unicode forms
let tStr1 = theString.precomposedStringWithCanonicalMapping
precomposedStringWithCanonicalMapping – Form C
decomposedStringWithCanonicalMapping – Form D
precomposedStringWithCompatibilityMapping – Form KC
decomposedStringWithCompatibilityMapping – Form KD

Attributed Text

Working with attributes in attributed text.

Embolden an attributed string and append it to another attributed string
let theBold = NSFont(name: "HelveticaNeue-Bold", size: 12.0)
let theTempAttrString = NSMutableAttributedString(string: theString)
let theRange = NSMakeRange(0, theTempAttrString.length)
theTempAttrString.addAttribute(NSFontAttributeName, value: theBold!, range: theRange)


Working with arrays. See also strings.

In Swift 3.0 but not 3.1
myArray = Array(Set(myArray))
In Swift 3.1, easier to build as a set in the first place, and then add to the set
var theSet = Set<String>()
theSet = Set<String>()

Swift Snippets 0: Introduction and Contents