Created
August 25, 2016 20:46
Star
You must be signed in to star a gist
Swift (2.3) Snippets
This file contains 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 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