[Swift]: Learning 2
swift
04/16/2019
Common usage for optional
The following two code blocks are equivalent
SWIFT
if emoji[card.identifier] != nill { return emoji[card.identifier]!} else { return "?"}
SWIFT
return emoji[card.identifier] ?? "?"
- nill means "the absence of a valid object."
- this only works for objects, not fur structures, basic C types, or enumeration values
- Swift's optionals let you indicate the absence of a value for any type at all, without the need for special constants.
Use of Dictionary
SWIFT
var emojiChoices = ["π¦", "π±", "π", "π","π", "π»", "π", "π¬", "π"]var emoji = [Int:String]()
func emoji(for card: Card) -> String { if emoji[card.identifier] == nil, emojiChoices.count > 0 { let randIndex = Int (arc4random_uniform(UInt32(emojiChoices.count))) emoji[card.identifier] = emojiChoices.remove(at: randIndex) }
return emoji[card.identifier] ?? "?" }
The following codes are equivalent, but first one is preferred
SWIFT
var emoji = [Int:String]()
SWIFT
var emoji = Dictionary<Int, String>()
- Dictionary is an implementation of Map like HashMap in java
- arc4random_uniform is a useful in generating random Int. But uses unsigned integer. Swift doesn't support automatic conversion, so casting is needed manually