Tuesday, May 17, 2016

String Functions

var str = "hello, playground"
print(str.capitalizedString) // Hello, Playground
let upperCase = str.uppercaseString // HELLO, PLAYGROUND
print(upperCase.lowercaseString) // hello, playground

let charSet = NSCharacterSet(charactersInString: ",")
let strArray = str.componentsSeparatedByCharactersInSet(charSet)
print(strArray[0]) // "hello"
print(strArray[1]) // " playground"

if str.containsString("hello") {
    print("hello found in string!")
}

print("Length of string: \(str.characters.count)")

var name = "   Mark    "
let trimThis = NSCharacterSet(charactersInString: " ")
name.stringByTrimmingCharactersInSet(trimThis) // "Mark"

let index = str.startIndex.advancedBy(7)
str.substringFromIndex(index) // "playground"
str.substringToIndex(index) // "hello, "

let norwayLike = str.stringByReplacingOccurrencesOfString("o", withString: "ø")
print(norwayLike) // "hellø, playgrøund"

let append = str.stringByAppendingString("!") // "hello, playground!"
let easier = str + "!" // "hello, playground!"

let age: Int = 25
let stringAge: String = String(age)
let stringAge2: String = "\(age)"

As you can see it still takes multiple lines to do in Swift that you can do in one line in most other languages. But I guess that is what extension classes are for!
(Swift 2.2)

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.

SwiftUI Search & Filter with Combine - Part 3 (iOS, Xcode 13, SwiftUI, 2...

In part 3 of the Searchable video series, I show you how to use Combine in #SwiftUI for the search and filter logic connected to the searcha...