Game Development Reference
In-Depth Information
var reversableString = "esrever"
println("The String is now \(reversableString.reverse())")
As you examine this code, you will see that it does look like a class or structure, but no-
tice the first line. There is no name. You have the keyword extension followed by the
class you are extending. After that, nothing else is different. To use the new extension,
you simply invoke the reverse() method as if it were part of the class. Copy this code
into your main.swift and run the program again. You will see the following output:
The String is now reverse
Generics
Generics have been around for a long time in languages such as Java, but they have been
missing on the Mac and iOS side. Swift solves this problem with its own implementation
of generics.
Generics allow you to write code that is both flexible and reusable. Generics are one of
the most interesting features of Swift. Let's dig in and see what generics are and how you
can leverage them to make your coding life easier.
func orderTwoNumbersAscending(num1: Int,
num2: Int) -> (lesser: Int,
greater: Int) {
if num1 > num2 {
return (num2, num1)
}
return (num1, num2)
}
var numbers = orderTwoNumbersAscending(10, 7)
println("\(numbers.lesser) < \(numbers.greater)")
This is a bit of a contrived example, but it will serve its purpose. In this snippet, you have
a function that takes two Int s, compares them, and returns a tuple with the numbers in
ascending order. If you run this, you will see the following output:
7 < 10
Search WWH ::




Custom Search