Skip to content

Instantly share code, notes, and snippets.

@patr1ck
Created August 25, 2016 20:46
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save patr1ck/fd6a3737ce60ae1c6131b896be392c12 to your computer and use it in GitHub Desktop.
Swift (2.3) Snippets
extension CollectionType {
/// Returns the element at the specified index iff it is within bounds, otherwise nil.
subscript (safe index: Index) -> Generator.Element? {
return indices.contains(index) ? self[index] : nil
}
}
extension Int {
func times(thing: Void -> Void) -> Void {
for _ in 0..<self {
thing()
}
}
}
extension String {
func rangeFromNSRange(nsRange : NSRange) -> Range<String.Index>? {
let from16 = utf16.startIndex.advancedBy(nsRange.location, limit: utf16.endIndex)
let to16 = from16.advancedBy(nsRange.length, limit: utf16.endIndex)
if let from = String.Index(from16, within: self),
let to = String.Index(to16, within: self) {
return from ..< to
}
return nil
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment