Skip to content

Instantly share code, notes, and snippets.

@s-aska s-aska/TwitterText.swift
Last active May 13, 2016

Embed
What would you like to do?
class TwitterText {
// swiftlint:disable:next force_try
static let linkDetector = try! NSDataDetector(types: NSTextCheckingType.Link.rawValue)
class func count(text: String, hasImage: Bool) -> Int {
let textLength = text.characters.count // 🍣 is 1
let objcLength = text.utf16.count // 🍣 is 2
let objcText = text as NSString
let objcRange = NSRange(location: 0, length: objcLength)
let matches = linkDetector.matchesInString(text, options: [], range: objcRange)
let urlLength = matches
.map { objcText.substringWithRange($0.range) as String }
.map { $0.characters.count }
.reduce(0, combine: +)
let shortURLLength = matches.count * 23
let imageURLLength = hasImage ? 24 : 0
return textLength - urlLength + shortURLLength + imageURLLength
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.