Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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