[:en]Swift: String[:]

[:en]Is string empty?

if textField1.text == "" || textField2.text == "" {
        // either textfield 1 or 2's text is empty
    }

 

Better way to handle option:

if let myString = defaults.stringForKey("indexselected") {
            if myString.isEmpty {
                
            }else {
            }

 

Convert String to Integer


let myInteger:Int? = Int(myString)

Find string in String?

var string = "hello Swift"

if string.rangeOfString("Swift") != nil{
    print("exists")
}

// alternative: not case sensitive
if string.lowercaseString.rangeOfString("swift") != nil {
    print("exists")
}

Find string in Array?

 let elements = [1,2,3,4,5]
 if elements.contains(5) {
 print("yes")

nth character of string

let str = "Hello, world!"

    let index = str.startIndex.advancedBy(4)
    str[index] // returns Character 'o'

    let endIndex = str.endIndex.advancedBy(-2)
    str[Range(start: index, end: endIndex)] // returns String "o, worl"

    str.substringFromIndex(index) // returns String "o, world!"
    str.substringToIndex(index) // returns String "Hell"

http://stackoverflow.com/questions/24092884/get-nth-character-of-a-string-in-swift-programming-language

Length of string:

let str = "Hello, world!"

   str.count

Remove all spaces in a string

let string = " a ab c "

let trimmed = string.stringByReplacingOccurrencesOfString(" ", withString: "")
print(trimmed)

// output should be "aabc"

// Note: string.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet()) will remove leading and trailing spaces

string.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet())

[:]

Print Friendly, PDF & Email
Scroll to Top