[Swift]: extension
swift
05/13/2019
Extensions in Swift
- extions allows to add variables/functions to other classe/struct/enum even if you don't have the source
- You can also use extensions to Frameworks (i.e. UIKit, Int, UIButton, UIViewController, etc)
Restrictions
- Can't re-implement method/property that already exists
- Properties in extensions can only be computed
- Caveat: Do not add var/func that does not make sense to the class/struct/enum
Example in Concentration
Outside the Concentration class:
SWIFT
extension Int { var arc4random: Int { return Int(arc4random_uniform(UInt32(self))) }}
- self is the Int that's sent
Changes made after creating extension
Before
SWIFT
let randomIndex = Int(arc4random_uniform(UInt32(emojiChoices.count)))emoji[card.identifier] = emojiChoices.remove(at: randomIndex)
After
SWIFT
emoji[card.identifier] = emojiChoices.remove(at: emojiChoices.count.arc4random)
Check for invalid inputs
SWIFT
extension Int { var arc4random: Int { if self > 0 { return Int(arc4random_uniform(UInt32(self))) } else if self < 0 { return -Int(arc4random_uniform(UInt32(self))) } else { return 0 } }}