Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
import Foundation
extension String
{
var length: Int {
get {
return countElements(self)
}
}
func contains(s: String) -> Bool
{
return self.rangeOfString(s) ? true : false
}
func replace(target: String, withString: String) -> String
{
return self.stringByReplacingOccurrencesOfString(target, withString: withString, options: NSStringCompareOptions.LiteralSearch, range: nil)
}
subscript (i: Int) -> Character
{
get {
let index = advance(startIndex, i)
return self[index]
}
}
subscript (r: Range<Int>) -> String
{
get {
let startIndex = advance(self.startIndex, r.startIndex)
let endIndex = advance(self.startIndex, r.endIndex - 1)
return self[Range(start: startIndex, end: endIndex)]
}
}
func subString(startIndex: Int, length: Int) -> String
{
var start = advance(self.startIndex, startIndex)
var end = advance(self.startIndex, startIndex + length)
return self.substringWithRange(Range<String.Index>(start: start, end: end))
}
func indexOf(target: String) -> Int
{
var range = self.rangeOfString(target)
if let range = range {
return distance(self.startIndex, range.startIndex)
} else {
return -1
}
}
func indexOf(target: String, startIndex: Int) -> Int
{
var startRange = advance(self.startIndex, startIndex)
var range = self.rangeOfString(target, options: NSStringCompareOptions.LiteralSearch, range: Range<String.Index>(start: startRange, end: self.endIndex))
if let range = range {
return distance(self.startIndex, range.startIndex)
} else {
return -1
}
}
func lastIndexOf(target: String) -> Int
{
var index = -1
var stepIndex = self.indexOf(target)
while stepIndex > -1
{
index = stepIndex
if stepIndex + target.length < self.length {
stepIndex = indexOf(target, startIndex: stepIndex + target.length)
} else {
stepIndex = -1
}
}
return index
}
func isMatch(regex: String, options: NSRegularExpressionOptions) -> Bool
{
var error: NSError?
var exp = NSRegularExpression(pattern: regex, options: options, error: &error)
if let error = error {
println(error.description)
}
var matchCount = exp.numberOfMatchesInString(self, options: nil, range: NSMakeRange(0, self.length))
return matchCount > 0
}
func getMatches(regex: String, options: NSRegularExpressionOptions) -> [NSTextCheckingResult]
{
var error: NSError?
var exp = NSRegularExpression(pattern: regex, options: options, error: &error)
if let error = error {
println(error.description)
}
var matches = exp.matchesInString(self, options: nil, range: NSMakeRange(0, self.length))
return matches as [NSTextCheckingResult]
}
private var vowels: [String]
{
get
{
return ["a", "e", "i", "o", "u"]
}
}
private var consonants: [String]
{
get
{
return ["b", "c", "d", "f", "g", "h", "j", "k", "l", "m", "n", "p", "q", "r", "s", "t", "v", "w", "x", "z"]
}
}
func pluralize(count: Int) -> String
{
if count == 1 {
return self
} else {
var lastChar = self.subString(self.length - 1, length: 1)
var secondToLastChar = self.subString(self.length - 2, length: 1)
var prefix = "", suffix = ""
if lastChar.lowercaseString == "y" && vowels.filter({x in x == secondToLastChar}).count == 0 {
prefix = self[0...self.length - 1]
suffix = "ies"
} else if lastChar.lowercaseString == "s" || (lastChar.lowercaseString == "o" && consonants.filter({x in x == secondToLastChar}).count > 0) {
prefix = self[0...self.length]
suffix = "es"
} else {
prefix = self[0...self.length]
suffix = "s"
}
return prefix + (lastChar != lastChar.uppercaseString ? suffix : suffix.uppercaseString)
}
}
}
"Awesome".contains("me") == true
"Awesome".contains("Aw") == true
"Awesome".contains("so") == true
"Awesome".contains("Dude") == false
"ReplaceMe".replace("Me", withString: "You") == "ReplaceYou"
"MeReplace".replace("Me", withString: "You") == "YouReplace"
"ReplaceMeNow".replace("Me", withString: "You") == "ReplaceYouNow"
"0123456789"[0] == "0"
"0123456789"[5] == "5"
"0123456789"[9] == "9"
"0123456789"[5...6] == "5"
"0123456789"[0...1] == "0"
"0123456789"[8...9] == "8"
"0123456789"[1...5] == "1234"
"Reply"[0...4] == "Repl"
"Hello, playground"[0...5] == "Hello"
"Coolness"[4...7] == "nes"
"Awesome".indexOf("nothin") == -1
"Awesome".indexOf("Awe") == 0
"Awesome".indexOf("some") == 3
"Awesome".indexOf("e", startIndex: 3) == 6
"Awesome".lastIndexOf("e") == 6
"Cool".lastIndexOf("o") == 2
var emailRegex = "[a-z_\\-\\.]+@[a-z_\\-\\.]{3,}"
"email@test.com".isMatch(emailRegex, options: NSRegularExpressionOptions.CaseInsensitive) == true
"email-test.com".isMatch(emailRegex, options: NSRegularExpressionOptions.CaseInsensitive) == false
var testText = "email@test.com, other@test.com, yet-another@test.com"
var matches = testText.getMatches(emailRegex, options: NSRegularExpressionOptions.CaseInsensitive)
matches.count == 3
testText.subString(matches[0].range.location, length: matches[0].range.length) == "email@test.com"
testText.subString(matches[1].range.location, length: matches[1].range.length) == "other@test.com"
testText.subString(matches[2].range.location, length: matches[2].range.length) == "yet-another@test.com"
"Reply".pluralize(0) == "Replies"
"Reply".pluralize(1) == "Reply"
"Reply".pluralize(2) == "Replies"
"REPLY".pluralize(3) == "REPLIES"
"Horse".pluralize(2) == "Horses"
"Boy".pluralize(2) == "Boys"
"Cut".pluralize(2) == "Cuts"
"Boss".pluralize(2) == "Bosses"
"Domino".pluralize(2) == "Dominoes"
@ryanbillingsley

This comment has been minimized.

Copy link

@ryanbillingsley ryanbillingsley commented Aug 12, 2014

@albertbori these are awesome. Only had to make one change for Beta 5, in

 func contains(s: String) -> Bool
 {
     return self.rangeOfString(s) ? true : false
 }

needs to test again nil

 func contains(s: String) -> Bool
 {
     return self.rangeOfString(s) != nil ? true : false
 }
@dsharmaradicle

This comment has been minimized.

Copy link

@dsharmaradicle dsharmaradicle commented Feb 20, 2015

Might be this will help to remove error now these days regarding optional binding:

 func isMatch(regex: String, options: NSRegularExpressionOptions) -> Bool
{
var error: NSError?
var exp = NSRegularExpression(pattern: regex, options: options, error: &error)
if let error = error {
println(error.description)
}
var matchCount = exp?.numberOfMatchesInString(self, options: nil, range: NSMakeRange(0, self.length))
return matchCount > 0
}
func getMatches(regex: String, options: NSRegularExpressionOptions) -> [NSTextCheckingResult]
{
var error: NSError?
var exp = NSRegularExpression(pattern: regex, options: options, error: &error)
if let error = error {
println(error.description)
}
var matches = exp?.matchesInString(self, options: nil, range: NSMakeRange(0, self.length))
return matches as [NSTextCheckingResult]
} 
@dstd

This comment has been minimized.

Copy link

@dstd dstd commented Jun 24, 2015

for the sake of i18n, please, don't use this kind of pluralize method >__<

@superarts

This comment has been minimized.

Copy link

@superarts superarts commented Jul 24, 2015

Totally disagree with @dstd: the word pluralize() indicates that it's an English thing. Otherwise it would be 复数() or pluralizar(), 不过当然啦,正常的中文里也没复数这种东西,孩儿们。

@SerxLee

This comment has been minimized.

Copy link

@SerxLee SerxLee commented Mar 28, 2016

advance is not use in switf 1.x
use advanceby now

@AlbertoMrFz

This comment has been minimized.

Copy link

@AlbertoMrFz AlbertoMrFz commented Nov 16, 2016

func trim() -> String
{
return self.trimmingCharacters(in: .whitespaces)
}

@khawajafarooq

This comment has been minimized.

Copy link

@khawajafarooq khawajafarooq commented Mar 3, 2017

Cool! Just contains have been replaced with following:
string.containsString("abc")

@reverocean

This comment has been minimized.

Copy link

@reverocean reverocean commented Mar 22, 2017

In Swift 3, subscript method should be change to following code:

extension String {
    subscript(r: Range<Int>) -> String {
        get {
            let startIndex = self.index(self.startIndex, offsetBy: r.lowerBound)
            let endIndex = self.index(self.startIndex, offsetBy: r.upperBound)

            return self[startIndex..<endIndex]
        }
    }

    subscript(r: ClosedRange<Int>) -> String {
        get {
            let startIndex = self.index(self.startIndex, offsetBy: r.lowerBound)
            let endIndex = self.index(self.startIndex, offsetBy: r.upperBound)

            return self[startIndex...endIndex]
        }
    }
}
@LanderlYoung

This comment has been minimized.

Copy link

@LanderlYoung LanderlYoung commented Jul 21, 2017

The String API of swift is way too much ugly and uncomfortable... T_T

@famictech2000

This comment has been minimized.

Copy link

@famictech2000 famictech2000 commented Jul 15, 2018

Substring does not work anymore!?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment