Last active
March 31, 2018 06:15
-
-
Save anitaa1990/343b81b554e8d11c2cfd44cf7d378069 to your computer and use it in GitHub Desktop.
A Swift extension class for String
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 | |
extension String { | |
/* | |
* split a string into n lines | |
* Eg: var s: String = "This is the first line.\nThis is the second line" | |
* print(s.lines[0]) -> This is the first line | |
*/ | |
var lines: [String] { | |
var result: [String] = [] | |
enumerateLines { line, _ in result.append(line) } | |
return result | |
} | |
/* | |
* check if a string is empty | |
* Eg: var s: String = "" | |
* print(s.isEmptyStr) -> true | |
*/ | |
var isEmptyStr:Bool { | |
return self.trimmingCharacters(in: NSCharacterSet.whitespaces).isEmpty | |
} | |
/* | |
* check if a string is equal to another string | |
* Eg: var s1: String = "string1" | |
* var s2: String = "string2" | |
* print(s1.isEqualToString(s2)) -> false | |
*/ | |
func isEqualToString(find: String) -> Bool { | |
return String(format: self) == find | |
} | |
/* | |
* convert a string to JSON | |
*/ | |
func toJSON() -> Any? { | |
guard let data = self.data(using: .utf8, allowLossyConversion: false) else { return nil } | |
return try? JSONSerialization.jsonObject(with: data, options: .mutableContainers) | |
} | |
/* | |
* get the index of a character in a string | |
* Eg: var s:String = "This is a single sentence. This is another sentence." | |
* let subString = s[s.indexOf(".")...] -> This will get the substring from the first index of '.' till the last index | |
* print(subString) -> This is another sentence. | |
*/ | |
func indexOf(_ input: String, | |
options: String.CompareOptions = .literal) -> String.Index? { | |
return self.range(of: input, options: options)?.lowerBound | |
} | |
/* | |
* get the last index of a character in a string | |
* Eg: var s:String = "This is a single sentence. This is another sentence." | |
* let subString = s[s.lastIndexOf(".")...] -> This will get the substring from the first index of '.' till the last index | |
* print(subString) -> . | |
*/ | |
func lastIndexOf(_ input: String) -> String.Index? { | |
return indexOf(input, options: .backwards) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment