Grant Emerson

Ad Infinitum and Beyond

Ad Infinitum and Beyond — SwiftMoji Entry #18

Swift offers range operators to express a span of values in shorthand. Both the closed range and half-open range operators are fairly well known. The former is expressed as a…b and includes the value b. The latter is expressed as a..<b and it excludes the last value. These two operators have a lesser-known cousin called the one-sided range. These ranges can be written as a… (for a to infinity), …a (for -infinity to a), or ..<a (for -infinity to one less than a). One-sided ranges can be used in subscripts, loops, and other situations such as the one below. In the following example, the seattle String is searched for the String.Index after that of the space. With that index, a one-sided range can be initialized that goes to positive infinity. In the case of sunny LA, we can replace the entire weather forecast with a simple emoji. The one-sided range allows replacingCharacters to remove from index till the endIndex is reached. Then it can simply insert the specified String.

import Foundation

var seattle = "Weather: ☁️-☁️-⛈-🌦-☁️-☁️-☁️"
let index = seattle.index(after: seattle.firstIndex(of: " ")!)
let la = seattle.replacingCharacters(in: index..., with: "Always ☀️") // Weather: Always ☀️
Tagged with: