Learning Swift Notes

Declare a string

let str = "Hello, playground "

Print a string

let str = "Hello, playground "
print(str)

Print a string 5 times, without tracking where you are in the loop, using a _

let str = "Hello, playground "
for _ in 1...5 {
 print(str)
}

or, replace the _ with a variable, if you do need to know.
And convert a Int to a String

let str = "Hello, playground "
for x in 1...5 {
print(str + String(x))
}

print a string using a function

let str = "Hello, playground "

func printMessage() {
 print(str)
}

for x in 1...5 {
 printMessage()
}

Print a string, using a function and passing the string to it

let str = "Hello, playground "

func printMessage(msg: String) {
 print(msg)
}

for x in 1...5 {
 printMessage(msg: str + String(x))
}

Print a string, using a function, with an optional string.
and printing either the string that was passed or the default string str

let str = "Hello, playground "

func printMessage(msg: String?) {
 print(msg ?? str)
}

for x in 1...5 {
 printMessage(msg: str + String(x))
}
NOTE: Although this is valid in most respects, you can’t actually pass nothing to the printMessage function for it to so that it prints the default message instead. But it shows the use if the nil-coalescing operator (??)

 

what next ?