Printing out "Hello World" is probably the most pointless thing you could spend time on. It wasn't always that way. Back in a time when getting ANY program to run on your computer was an achievement it made sense to have a consistent test to show that everything kind of worked.
Now a days all it takes is to download Xcode and make a new Swift playground and enter
print("Hello World")
No imports needed!
That took a lot less than 2 minutes!
Good thing we aren't going to stop there!
A much better version is to print it vertically using a loop. (for extra credit try using the map function!)
H
e
l
l
oW
o
r
l
d
This helps you learn basic looping and string iteration.
let str = "Hello World"
for c in str {
print(c)
}
Makes sense! Still not 2 minutes
The last "Hello World" challenge I like to have people who are brand new to coding in Swift do is to start with the string "Hello World" and transform it by making the even letters upper case and the odd letter lowercase -> "hElLo wOrLd"
let str = "Hello World"
var outstr = ""
var i = 1
for c in str {
var tempStr = String(c)
if i % 2 == 0 {
tempStr = tempStr.uppercased()
}
else {
tempStr = tempStr.lowercased()
}
outstr.append(tempStr)
i += 1
}
print(outstr)
Explain?
- Create a string constant of "Hello World"
- Create a variable to hold the output
- Create a variable to hold the current letter count
- Loop through all the characters in the string
- Turn the character back into a String
- Modulus divide the count by 2 to find out if it is even or odd (If you don't understand click here)
- Stick the upper or lower case letter on the end of our output string
- Add 1 to the count since we are moving on to the next character
- Back to step 5 until we have finished with all the characters
You could improve that by...
It's a beginners example. Don't add complexity!
But at least use a bitwise and for speed!
You're not a beginner stop reading Hello World articles.