Last active
May 27, 2016 09:23
-
-
Save avdyushin/1310570fa5ca4d7cd532f4d59e8eeb46 to your computer and use it in GitHub Desktop.
Swift extension for string manipulation
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
// | |
// String 1.0 | |
// Created by Caleb Hess on 2/22/16. | |
// | |
public extension String { | |
public var count: Int { | |
return self.characters.count | |
} | |
public var asURL: NSURL? { | |
return NSURL(string: self) | |
} | |
public subscript (i: Int) -> String { | |
return String(self[i] as Character) | |
} | |
public subscript (r: Range<Int>) -> String { | |
return substringWithRange(Range(start: startIndex.advancedBy(r.startIndex), end: startIndex.advancedBy(r.endIndex))) | |
} | |
public func split(sepearator: String) -> [String] { | |
return self.componentsSeparatedByString(sepearator) | |
} | |
public func trim() -> String { | |
return self.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet()) | |
} | |
public func replace(target: String, with: String) -> String { | |
return self.stringByReplacingOccurrencesOfString(target, withString: with) | |
} | |
public func replace(values: [String:String]) -> String { | |
var result = self | |
for (target, with) in values { | |
result = result.replace(target, with: with) | |
} | |
return result | |
} | |
public func indexOf(target: String) -> Int { | |
if let range = self.rangeOfString(target) { | |
return self.startIndex.distanceTo(range.startIndex) | |
} else { | |
return -1 | |
} | |
} | |
public func contains(target: String) -> Bool { | |
return self.indexOf(target) != -1 | |
} | |
} | |
// -------------------- | |
// examples of use | |
let str = "hello world" | |
str.count // 11 | |
str[1] // "e" | |
str[1...3] // "ell" | |
str.split(" ") // ["hello", "world"] | |
str.trim() // "hello world" | |
str.replace("h", with: "j") // "jello world" | |
str.replace(["h": "j", "world": "land"]) // "jello land" | |
str.indexOf("world") // 6 | |
str.contains("jupiter") // false | |
"https://example.com".asURL // NSURL? |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment