Skip to content

Instantly share code, notes, and snippets.

@Slowhand0309
Created August 17, 2019 09:26
Show Gist options
  • Save Slowhand0309/ea9cf4be918c583caa0954dabdbb5bb5 to your computer and use it in GitHub Desktop.
Save Slowhand0309/ea9cf4be918c583caa0954dabdbb5bb5 to your computer and use it in GitHub Desktop.
[Swift extensions] #iOS
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]
}
}
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