Last active
September 27, 2018 18:28
-
-
Save pvn/7b978cd3c6b28c9d6d5b807de7026a15 to your computer and use it in GitHub Desktop.
String extension using swift
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 String | |
{ | |
var length: Int { | |
get { | |
return self.count | |
} | |
} | |
var startToEndRange: Range<String.Index> { | |
get { | |
let start = self.index(self.startIndex, offsetBy: 0) | |
let end = self.index(self.startIndex, offsetBy: self.length) | |
return start..<end | |
} | |
} | |
func contains(s: String, option: String.CompareOptions) -> Bool { | |
return (self.range(of: s, options: option, range: self.startToEndRange, locale: nil) != nil) | |
} | |
func replace(target: String, withReplaceString: String) -> String { | |
return self.replacingOccurrences(of: target, with: withReplaceString, options: .literal, range: nil) | |
} | |
func trimWhiteSpace() -> String { | |
return self.trimmingCharacters(in: .whitespaces) | |
} | |
func toDictionary() -> [String: Any] { | |
if let data = self.data(using: .utf8) { | |
do { | |
return (try JSONSerialization.jsonObject(with: data, options: []) as? [String: Any])! | |
} catch { | |
print(error.localizedDescription) | |
} | |
} | |
return [:] | |
} | |
func hostWithScheme() -> String { | |
let url = URL.init(string: self) | |
return "\(url!.scheme ?? "")://\(url!.host ?? "")" | |
} | |
func textSize(textFont: UIFont) -> CGSize { | |
let fontAttributes = [NSAttributedStringKey.font: textFont] | |
return (self as NSString).size(withAttributes: fontAttributes as [NSAttributedStringKey : Any]) | |
} | |
} | |
/* Output | |
let original = "original" | |
let duplicate = "orig" | |
print("Contains \(original.contains(s: duplicate, option: .caseInsensitive))") // true | |
print("Replace \(original.replace(target: "gin", withReplaceString: "duplicate"))") // ori[duplicate]al | |
let original = " original " | |
let duplicate = "orig" | |
print("|\(original)|") // | original | | |
print("|\(original.trimWhiteSpace())|") // |original| | |
let str = "{\"name\":\"James\"}" | |
let dict = str.toDictionary() | |
print("Dict \(dict)") // Dict ["name": James] | |
let urlString = "https://example.com/json/getToken" | |
print("Url \(urlString.hostWithScheme())") // https://example.com | |
// button is an instance of UIButton and | |
// button font font-family: ".SFUIText"; font-weight: normal; font-style: normal; font-size: 18.00pt | |
let size = title.textSize(textFont: (button.titleLabel?.font)!) | |
print(size) // (42.609375, 21.48046875) | |
*/ | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment