​Swift is a powerful and instinctive coding language for macOS, iOS, watchOS and tvOS....

Page 232

Swift

tos.push("Type Parameters") println(tos.items)

tos.push("Naming Type Parameters") println(tos.items) When we run the above program using playground, we get the following result: [Swift] [Swift, Generics] [Swift, Generics, Type Parameters] [Swift, Generics, Type Parameters, Naming Type Parameters]

Where Clauses Type constraints enable the user to define requirements on the type parameters associated with a generic function or type. For defining requirements for associated types 'where' clauses are declared as part of type parameter list. 'where' keyword is placed immediately after the list of type parameters followed by constraints of associated types, equality relationships between types and associated types. protocol Container { typealias ItemType mutating func append(item: ItemType) var count: Int { get } subscript(i: Int) -> ItemType { get } }

struct Stack<T>: Container { // original Stack<T> implementation var items = [T]() mutating func push(item: T) { items.append(item) }

mutating func pop() -> T { return items.removeLast() } 220


Issuu converts static files into: digital portfolios, online yearbooks, online catalogs, digital photo albums and more. Sign up and create your flipbook.