Created
August 17, 2019 09:26
-
-
Save Slowhand0309/ea9cf4be918c583caa0954dabdbb5bb5 to your computer and use it in GitHub Desktop.
[Swift extensions] #iOS
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public extension Array { | |
/// Secure access at index. | |
/// | |
/// let array = [1, 2] | |
/// array[safe: 0] // Optional(1) | |
/// array[safe: 1] // Optional(2) | |
/// array[safe: 2] // nil | |
subscript (safe index: Index) -> Element? { | |
return indices.contains(index) ? self[index] : nil | |
} | |
/// Set the value to the beginning of the array. | |
/// | |
/// [2, 3, 4, 5].prepend(1) -> [1, 2, 3, 4, 5] | |
public mutating func prepend(_ newElement: Element) { | |
insert(newElement, at: 0) | |
} | |
/// first vs second. | |
public var second: Element? { | |
return self[safe: 1] | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
extension Int { | |
/// Comma notation separated by three digits 1000000 -> 1,000,000 | |
public var commaFormatted: String { | |
if self < 0 { | |
return "0" | |
} | |
let formatter = NumberFormatter() | |
formatter.numberStyle = .decimal | |
let commaString = formatter.string(from: self as NSNumber) | |
return commaString ?? "\(self)" | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment