[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
@IBAction func touchCard(ExternalArg InternalArg: UIButton) {
}
Swift can have different types of argument.
- Having one argument: used in both outside and inside the function
- 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
@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
@IBAction func touchCard(oneArg sender: UIButton) -> int {
}
Swift uses -> to denote the return value of a func
Int?
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
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 !:
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.
class Concentration{
}
Whenever creating a class, always think about what the public API(Application Programming Interface) would look like
for loop
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
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
- value type: when gets passed in argument, used in array, or assigned to another variable, it gets 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.