[Swift]: Learning 1

swift

04/16/2019


Start

I have recently started to learn Swift in Xcode--the following swift posts will be coming from a free course provided by Standford University.

Syntax: Argument

SWIFT
@IBAction func touchCard(ExternalArg InternalArg: UIButton) {
}

Swift can have different types of argument.

  1. Having one argument: used in both outside and inside the function
  2. Having two arguments: external/internal arguments. Former is used outside the function and latter is used inside the function.

Here's an example of usage of external / internal names

SWIFT
@IBAction func touchCard(_ sender: UIButton){
flipCard(withEmoji: "👻", on: sender)
}
func flipCard(withEmoji emoji: String, on button: UIButton){
if button.current = emoji {
}
}

func touchCard uses withEmoji(external name) while func flipCard uses emoji(internal name).

Return value

SWIFT
@IBAction func touchCard(oneArg sender: UIButton) -> int {
}

Swift uses -> to denote the return value of a func

Int?

SWIFT
func firstIndex(of elemment: UIButton) -> Int?

Int? is not an int. This return value is an optional, different type entirely from int. Optional has two states: set or not set.

Optional

SWIFT
let cardNum = cardButtons.firstIndex(of: sender)!

Putting ! at the end assumes that the optional is set. By doing this, it may cause a fatal error when the optional is not set. Thus, it may be a better practice to have if/else block w/o !:

SWIFT
if let cardNum = cardButtons.firstIndex(of: sender){
} else{
}

Creating a model (class)

In Xcode, command + N to create a new file to create a new class.

SWIFT
class Concentration{
}

Whenever creating a class, always think about what the public API(Application Programming Interface) would look like

for loop

SWIFT
init(numPairs: Int){
// 0..<numPairs: does not include numPairs. Use ... for inclusive
// Use _ when we don't care about what identifier is
for _ in 0..<numPairs {
let card = Card()
}
}

struct

SWIFT
struct Card {
var isFaceUp = false
var isMatched = false
static var identifierFactory = 0
init() {
self.identifier = Card.getUniqueIdentifier()
}
static func getUniqueIdentifier() -> Int {
identifierFactory += 1
return Card.identifierFactory
}
}

struct and class are similar but:

  • No inheritance in struct
  • structs are value types and classes are reference types
    • value type: when gets passed in argument, used in array, or assigned to another variable, it gets copied
      • Note: Array Int String Dictionary are structs; they get constantly get copied
  • In contrast, class is a reference type. It lives in heap with pointer to it. When you pass somthing you pass the pointer not the actual thing.

WRITTEN BY

Keeping a record