Created
November 23, 2017 16:49
-
-
Save hebertialmeida/d868bd58efe8b5240e4ef8b542107099 to your computer and use it in GitHub Desktop.
Twitter text counter 280 characters
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
import Foundation | |
struct WeightRange { | |
let range: ClosedRange<UInt32> | |
let weight: Int | |
} | |
struct TwitterText { | |
static func lengthOf(tweet: String) -> Int { | |
let defaultWeight = 200 | |
let scale = 100 | |
let ranges = [ | |
WeightRange(range: 0...4351, weight: 100), | |
WeightRange(range: 8192...8205, weight: 100), | |
WeightRange(range: 8208...8223, weight: 100), | |
WeightRange(range: 8242...8247, weight: 100) | |
] | |
let (cleanText, urlLength) = cleanAndCountURLs(text: tweet) | |
var weightedLength = urlLength * scale | |
for char in cleanText.unicodeScalars { | |
var weight = defaultWeight | |
for item in ranges where item.range ~= char.value { | |
weight = item.weight | |
continue | |
} | |
weightedLength += weight | |
} | |
weightedLength /= scale | |
return weightedLength | |
} | |
private static func cleanAndCountURLs(text: String) -> (String, Int) { | |
var output = text | |
var lenght = 0 | |
let detector = try! NSDataDetector(types: NSTextCheckingResult.CheckingType.link.rawValue) | |
let matches = detector.matches(in: text, options: [], range: NSRange(location: 0, length: text.utf16.count)) | |
matches.forEach { | |
output = (text as NSString).replacingCharacters(in: $0.range, with: "") | |
lenght += 23 | |
} | |
return (output, lenght) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@annjaun I think any URLs on twitter should count as 23, but yeah, detecting this kind of URL will probably require a custom regex implementation if it is not handled by
NSDataDetector
.Twitter also count es.pn as 23: