Quick is just a powerful and user-friendly coding language for macOS, iOS, watchOS and tvOS....

Page 227

Swift

println("Before Swapping Int values are: \(numb1) and \(numb2)") exchange(&numb1, &numb2) println("After Swapping Int values are: \(numb1) and \(numb2)")

var str1 = "Generics" var str2 = "Functions"

println("Before Swapping String values are: \(str1) and \(str2)") exchange(&str1, &str2) println("After Swapping String values are: \(str1) and \(str2)") When we run the above program using playground, we get the following result: Before Swapping Int values are: 100 and 200 After Swapping Int values are: 200 and 100 Before Swapping String values are: Generics and Functions After Swapping String values are: Functions and Generics The function exchange() is used to swap values which is described in the above program and <T> is used as a type parameter. For the first time, function exchange() is called to return 'Int' values and second call to the function exchange() will return 'String' values. Multiple parameter types can be included inside the angle brackets separated by commas. Type parameters are named as user defined to know the purpose of the type parameter that it holds. Swift provides <T> as generic type parameter name. However type parameters like Arrays and Dictionaries can also be named as key, value to identify that they belong to type 'Dictionary'. Generic Types struct TOS<T> { var items = [T]() mutating func push(item: T) { items.append(item) }

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

215


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