[iOS] Swift Basic

Code Structure

  • ViewController:

    • IBOutlet: control + click on element in storyboard and drop the mouse into viewController file, click connect
    • IBAction: control + click on the button and drag it to the code -> pops up action editing panel
  • Storyboard

1
2
3
4
5
6
7
8
9
10
11
12
13
class ViewController: UIViewController {
@IBOutlet weak var diceImageViewOne: UIImageView!

override func viewDidLoad() {
super.viewDidLoad()

diceImageView1.image = #imageLiteral(resourceName: "DiceOne")
}

@IBAction func rollButtonPressed(_ sender: UIButton) {
diceImageViewOne.image = #imageLiteral(resourceName: "DiceFour")
}
}
  • String
1
var s = "some example string with \(variable)"
  • Range operator
1
2
3
4
5
6
7
let randomNumber = Int.random(in: 1 ... 3) //  closed range [1, 3]
Int.random(in: 1 ..< 3) // half open range operator [1, 3)
Int.random(in: ...3) // one sided range [, 3] anything smaller than 3 including 3
Float.random(in: 1 ... 3) // float random
Bool.random()
array.randomElement()
array.shuffle()
  • Switch
1
2
3
4
5
6
7
8
9
10
switch score {
case 81...100:
print("first range")
case 41..<81:
print("second range")
case ...40:
print("thrid range")
default:
print("Error")
}
  • Dictionary
1
var dict : [String: Int] = ["Key": value]
  • Optionals
1
2
3
4
5
6
var hardness: String? = nil
hardness = "something"
// unwrap optional
if hardness != nil {
var unwrapped = hardness!
}
  • Timer
1
2
3
4
5
6
7
8
9
10
var timer = Timer()

timer.invalidate() // reset timer
timer = Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(updatedTimer), repeats: true)

@obj func updateTimer() { // obj: objective-c api exposed
if secondsRemaining > 0 {
secondsRemaining -= 1
}
}
  • Float
1
2
3
4
5
6
7
8
9
let a = 5
let b = 2

print(a / b) // 2

let a: Float = 5
let b: Float = 2

print(a / b) // 2.5
  • Struct

Struct name starts with a capital letter

1
2
3
4
5
6
7
8
9
10
11
12
struct Town {
let name = "Town name"
var citizens = []
var resources = ["Grain": 100, "Ore": 42, "Wool": 20]

func fortify() {
// do something
}
}

var myTown = Town()
print(myTown.name)