Game Development Reference
In-Depth Information
there are only six elements in the array, but the while would still try to run that first
time.
var colors = ["red", "blue", "green", "black", "blue",
"orange"]
var index = 0
do {
println("The color is : \(colors[index])")
index++
} while index < colors.count
Functions
Swift and Objective-C functions have a very different syntax. The basic syntax of a Swift
function is as follows:
func catTwoWords(word1: String, word2: String) ->String {
return "\(word1)\(word2)"
}
println(catTwoWords("Hello", "World"))
You start the function declaration with the keyword func followed by the function name.
After this, you have a named list of parameters with their respective types followed by the
return arrow ( -> ) and the return type of the function. The body of the function is repres-
ented by opening and closing braces ( {} ) just like Objective-C.
This function is named catTwoWords() . It takes two String parameters named
word1 and word2 . And it returns a String . Calling a Swift function is much like call-
ing a C function. You use the name of the function with your parameter list surrounded by
parentheses.
Replace the body of your main.swift file with this code and run it. You will see this
output:
HelloWorld
If you want to create a function that has no parameters or return types, you simply omit
them.
Search WWH ::




Custom Search