Last active
July 31, 2019 15:48
-
-
Save tomestephens/126148a4cc1756853d037c0a3d78f6e1 to your computer and use it in GitHub Desktop.
Learning Swift -- some string manipulation in a playground
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 UIKit | |
extension StringProtocol { | |
func ranges(of: String) -> [Range<Index>] { | |
var ranges: [Range<Index>] = [] | |
var range = self.range(of: of) | |
while let r = range { | |
ranges.append(r) | |
range = self[r.upperBound...].range(of: of) | |
} | |
return ranges | |
} | |
func substring(_ start: Index, _ end: Index? = nil) -> String { | |
guard let e = end else { | |
return String(self[start...]) | |
} | |
return String(self[start..<e]) | |
} | |
} | |
func getAttributes(isBold: Bool) -> [NSAttributedString.Key: Any] { | |
let font = isBold ? UIFont.boldSystemFont(ofSize: 12.0) : UIFont.systemFont(ofSize: 12.0) | |
return [NSAttributedString.Key.font: font] | |
} | |
func boldText(src: String, toBold: String) -> NSAttributedString { | |
let ranges = src.lowercased().ranges(of: toBold.lowercased()) | |
if ranges.isEmpty { | |
return NSAttributedString(string: src, attributes: getAttributes(isBold: false)) | |
} | |
let text = NSMutableAttributedString(string: String(src[..<ranges[0].lowerBound]), attributes: getAttributes(isBold: false)) | |
for i in 0..<ranges.count { | |
if i > 0 && ranges[i-1].upperBound < ranges[i].lowerBound { | |
text.append(NSAttributedString(string: src.substring(ranges[i-1].upperBound, ranges[i].lowerBound), attributes: getAttributes(isBold: false))) | |
} | |
text.append(NSAttributedString(string: src.substring(ranges[i].lowerBound, ranges[i].upperBound), attributes: getAttributes(isBold: true))) | |
} | |
text.append(NSAttributedString(string: src.substring(ranges[ranges.count-1].upperBound), attributes: getAttributes(isBold: false))) | |
return text | |
} | |
print(boldText(src: "Congratulations!", toBold: "winner")) | |
print(boldText(src: "Congratulations! You're a winner!", toBold: "winner")) | |
print(boldText(src: "Winner, winner, chicken dinner!", toBold: "winner")) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment