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)


An array is an ordered collection of elements of the same type, and they are used for pretty much anything that requires storing things in a certain order, such as the contents of lists in apps. It works like similar types in other languages.

Working with Arrays

Here are some of the most common operations on arrays:

  • Create an array:

    let a = [0,1,2,3,4] // array literal
  • Join two arrays:

    var b = a + [5,6]
  • Repeat a value:

    let c = Array(repeating: 4.1, count: 3)
  • Create an array from any sequence (a String is a Sequence of Character):

    var d = Array("The ☀ and 🌙 ")
  • Add values to the end of an array:

    b.append(10) // append one element
  • Append an entire array:

    b += a
    b.append(contentsOf: a) // append a sequence
  • Get the length of an array:

  • Iterate over all elements:

    for nr in b {
             // do something with 'nr'

Here are their abilities, represented by some of the protocols they conform to:

  • BidirectionalCollection can go backwards from any index (except...