What I learned today:
- Basics – Loops.
- Each button in Xcode has a tag.
- Basics – Do/Catch Statement.
- Playing sound in Swift.
- Global & Local Scope
Loops
// Will print numbers in a loop
for number in 1...100 {
print(number)
}
// Starts from reverse
for number in (1...100).reversed {
print(number)
}
Buttons – Tags
Each button in Xcode has a tag. We can use sender.tag to get information regarding which button was pressed.
// Print to the console which button was pressed
print(sender.tag)
// Perform different tasks as per different button pressed
if sender.tag == 1 {
print("You pressed button one.")
} else if sender.tag == 2 {
print("You pressed button two.")
} else {
print("You pressed the other button.")
}
- Extra : If you need to know anything about a function which you don’t understand in Xcode, you can hold alt key in Mac and click on that function and Xcode will display it’s details.
Global & Local Scope
- If a variable is declared inside a function then it is considered to have local scope, which means it cannot be used outside that function.
- Global scope – the variable is declared normally outside any function and can be detected by Xcode and used throughout the code.
Do/Catch Statement
// Try to do something. If not possible then throw an error.
do {
try
} catch {
print(error)
}
Playing sound in Swift
// Firstly we need to import AudioToolBox
import AudioToolbox
// nameofsoundfile refers to the filname, extension can be .wav, .mp3 etc
if let soundURL = Bundle.main.url(forResource: "nameofsoundfile", withExtension: "wav") {
var mySound: SystemSoundID = 0
AudioServicesCreateSystemSoundID(soundURL as CFURL, &mySound)
// Play
AudioServicesPlaySystemSound(mySound);