So I’ve decided to do some more work on learning Swift. I’ve got hold of a couple of books that take you through a range of different projects in order to teach you the basics of Swift plus all the other bits and pieces, such as Interface Builder and XCode. I’ve going to build the projects in real time, and then reflect on what I’ve learned, with the aim of integrating that with what I did. It’s my hope that this will help embed the learning – but we will see.
The first project (after a brief introduction to the syntax of Swift via XCode playgrounds) is a variation of the traditional Hello World. The purpose of the finished project is to create a an app which consists of single view. In the view there are four buttons. The buttons are different colours, and if you click on each button, it will tell you what’s on the actual button (i.e. explain the meaning of the emoji on the button).
Below is the finished code. This is from the View Controller file (a single file because this is a single view file). I’m going to annotate it to explain what’s going on.
import UIKit
// brings in the UKKit library - need for @IBAction (links to main.storyboard and view controllers)
class ViewController: UIViewController {
// defines a new class than inherits from UIView controller.
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func showMessage(sender: UIButton) {
// This creates a link between this file and the storyboard file. It's a function called showMessage, that is linked to a button. The button is called sender.
var emojiDict = ["?": "Ghost", "?": "Robot", "?": "Angry", "?": "Nerdy", "?": "Alien monster"]
// This creates a dictionary with emojis as keys, and their meaning as values.
let selectedButton = sender
// We create constant called selectedButton and assign it to the parameter passed into the function - sender.
if let wordToLookup = selectedButton.titleLabel?.text {
// Now we create another constant called wordToLookup. We assign the value of that constant to the emoji text on the button that we tapped by accessing the titleLabel.text property.
let meaning = emojiDict[wordToLookup]
//Then, we assign another constant, meaning, to the value from the EmojiDict dictionary related to the key we're looking up.
let alertController = UIAlertController(title: "Meaning", message: meaning, preferredStyle: UIAlertControllerStyle.alert)
// Here we create an object of UIAlertController type, and pass in the appropriate parameters.
alertController.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.default, handler: nil))
// Here we add an action box to the alertController.
present(alertController, animated: true, completion: nil)
//Now we present the alert controller.
}
}
}