Generics

Heads up... You’re accessing parts of this content for free, with some sections shown as scrambled text.

Heads up... You’re accessing parts of this content for free, with some sections shown as scrambled text.

Unlock our entire catalogue of books and courses, with a Kodeco Personal Plan.

Unlock now

Generics

Functions

You can follow along with this section by creating a blank iOS playground in Xcode. Replace the boilerplate with this code:

import UIKit

func swapTwoValues(a: Int, b: Int) -> (a: Int, b: Int) {
  let temp = a
  let newA = b
  let newB = temp
  return (newA, newB)
}

swapTwoValues(a: 42, b: 5)
func swapTwoValues(a: String, b: String) -> (a: String, b: String) {
  let temp = a
  let newA = b
  let newB = temp
  return (newA, newB)
}

swapTwoValues(a: "begin", b: "finish")
// Don't copy this in your playground
func swapTwoValues(a: Any, b: Any) -> (a: Any, b: Any) {
  let temp = a
  let newA = b
  let newB = temp
  return (newA, newB)
}

var name = "Tim Cook"
var phoneNumber = 5141111111
swapTwoValues(a: name, b: phoneNumber)
func swapValues<T>(a: T, b: T) -> (a: T, b: T) {
  let temp = a
  let newA = b
  let newB = temp
  return (newA, newB)
}

swapValues(a: 42, b: 5)
swapValues(a: "begin", b: "finish")

Generic Types

All Swift collections are generic types. For example, this array initializer creates an array containing the elements of a sequence:

init<S>(_ s: S) where Element == S.Element, S : Sequence
protocol Sequence<Element>

Creating a Generic Type

Here’s a generic struct you could use to store and retrieve any type from UserDefaults:

struct Setting<T> {
  let key: String

  var value: T? {
    get {
      UserDefaults.standard.value(forKey: key) as? T
    } set {
      UserDefaults.standard.setValue(newValue, forKey: key)
    }
  }
}
var volume = Setting<Float>(key: "audioVolume")
volume.value = 0.5
let setting: Setting<Int> = .init(key: "myKey")

Extending a Generic Type

You can extend generic types the same way you can extend a normal class, struct, enum, or protocol. In the extension of a generic type, you have access to its type parameters:

extension Setting {
  mutating func save(from untypedValue: Any) {
    if let value = untypedValue as? T {
      self.value = value
    }
  }
}
See forum comments
Download course materials from Github
Previous: Generics - Introduction Next: Constraints