Book Image

Beginning Swift

By : Rob Kerr, Kåre Morstøl
Book Image

Beginning Swift

By: Rob Kerr, Kåre Morstøl

Overview of this book

Take your first foray into programming for Apple devices with Swift.Swift is fundamentally different from Objective-C, as it is a protocol-oriented language. While you can still write normal object-oriented code in Swift, it requires a new way of thinking to take advantage of its powerful features and a solid understanding of the basics to become productive.
Table of Contents (10 chapters)

Substring


SubString is for strings what ArraySlice is for arrays: a view of a part of a string, where its startIndex and endIndex are indices into the original string. It conforms to the same protocols as String:

StringProtocol contains many of the common text operations, so when you write functions that take a string parameter you can often use StringProtocol instead to also accept substrings. When you do, you have to use generics, as shown here:

func foo<S: StringProtocol>(s: S) {
  // use 's' almost like a normal string.
}

Just as with ArraySlice, substrings keep a reference to the entire string, so when you are done processing substrings you should turn them into normal strings and allow the original string to be released (if nothing else is using it):

String(substring)

Creating Substrings

Substrings can be created in many different ways:

  • We can create substrings by passing a range of indices to a string subscript:

    string[from..<upTo]
    string[from...upToAndIncluding...