One Quickie


(NSString->Swift)
Truncating a string with the first N characters. Good as of Swift 3.
func truncate(string: String, toCount count: Int) -> String {
    if let endIndex = string.index(string.startIndex,
                                   offsetBy: count,
                                   limitedBy: string.endIndex) {
        let range = string.startIndex ..< endIndex
        let result = string[range]
        
        if result == string { // It's exactly |count| thingies big
            return string
        } else {
            return result + "..."
        }
    }
    return string
}



borkware home | products | miniblog | rants | quickies | cocoaheads
Advanced Mac OS X Programming book

webmonster@borkware.com