Do you need help on a specific subject? Use the contact form (Request a blog entry) on the right hand side.

2015-04-05

Swift extensions: String function fixIndex

In this post I will keep track of general purpose extensions for the Swift String type.

fixIndex

extension String {
    
    /// This function fixes the associated endIndex of the given index by returning a new index with the same value and a new associated endIndex.
    
    func fixIndex(index: String.Index) -> String.Index {
        let kludge = distance(startIndex, index)
        return advance(startIndex, kludge)
    }
}

Example usage:

var string = "12"
var index = string.startIndex.successor().successor()

string += "34"

// index = index.successor().successor() ==>> gives us an "EXC_BAD_INSTRUCTION"

index = string.fixIndex(index)

index = index.successor().successor() // OK

isLowercaseCharacterAtIndex

extension String {
    
    /// Returns true if the character at the given index is a lowercase character as defined in the lowercase character set. Works for UTF16 characters only.

    func isLowercaseCharacterAtIndex(index: String.Index) -> Bool {
        return NSCharacterSet.lowercaseLetterCharacterSet().characterIsMember(String(self[index]).utf16[String.UTF16Index(0)])
    }

}

Example usage:

let str = "1 gF🌵"

for i in str.startIndex ... str.endIndex.predecessor() {
    print("\(str.isLowercaseCharacterAtIndex(i)), ")

}

Prints:

false, false, true, false, false,

isUppercaseCharacterAtIndex

extension String {
    
    /// Returns true if the character at the given index is an uppercase character as defined in the uppercase character set. Works for UTF16 characters only.

    func isUppercaseCharacterAtIndex(index: String.Index) -> Bool {
        return NSCharacterSet.uppercaseLetterCharacterSet().characterIsMember(String(self[index]).utf16[String.UTF16Index(0)])
    }

}

Example usage:

let str = "1 Fg🌵"

for i in str.startIndex ... str.endIndex.predecessor() {
    print("\(str.isUppercaseCharacterAtIndex(i)), ")

}

Prints:

false, false, true, false, false,

replaceCharacterAtIndex

extension String {
    
    /// Replaces the character at the specified index with the given character. Returns true if the string was changed, false if not.
    
    mutating func replaceCharacterAtIndex(index: String.Index, with char: Character) -> Bool {
        if index == endIndex { return false }
        if self[index] == char { return false }
        let range = Range(start: index, end: index.successor())
        self.replaceRange(range, with: String(char))
        return true
    }

}

Example usage:

var str = "123456789"
str.replaceCharacterAtIndex(str.startIndex.successor(), with: "F")
print(str)

Prints:

"1F3456789"

changeCaseOfCharacterAtIndex

This extension needs the three preceding extensions.

extension String {
        
    /// Changes the case of the character at the specified index. Returns true if the string was changed, false if not.
    
    mutating func changeCaseOfCharacterAtIndex(index: String.Index) -> Bool {
        if isLowercaseCharacterAtIndex(index) {
            return self.replaceCharacterAtIndex(index, with: String(self[index]).uppercaseString[startIndex])
        } else if isUppercaseCharacterAtIndex(index) {
            return self.replaceCharacterAtIndex(index, with: String(self[index]).lowercaseString[startIndex])
        } else {
            return false
        }
    }
}

Happy coding...

Did this help?, then please help out a small independent.
If you decide that you want to make a small donation, you can do so by clicking this
link: a cup of coffee ($2) or use the popup on the right hand side for different amounts.
Payments will be processed by PayPal, receiver will be sales at balancingrock dot nl
Bitcoins will be gladly accepted at: 1GacSREBxPy1yskLMc9de2nofNv2SNdwqH

We don't get the world we wish for... we get the world we pay for.

No comments:

Post a Comment