Swift language: Strings

What is string? String is an ordered collection of characters. Like NSString in objective C we have String type in swift and for characters we have character type. String is a combination of characters.

You can create string as

var  myName = “iPhone Development”

To initialize an empty string

var  myName = ” ”

var initializemyName = String()

Here myName and initializemyName are both empty string and the only difference between them is that myName is literal string and the second line is a syntax to initialize a string in swift.

Strings can be mutated in swift as we are doing in objective C.

var myName = ”iPhone”

myName += “Development”

Now the output of myName would be

println(“output of myName= (myname)”)

It will print output of myName= iPhone Development

String declare as variable or var can be mutated and string declared as constant or let are immutable strings. The below code will throw error at compile time that a constant string cannot be modified

let myName = ”iPhone”

myName += “Development”

You can check for empty string by using isEmpty property of a string, this will return a Boolean value to you

var emptyString = “”

if emptyString.isEmpty
{
    println(“String is empty”)
}

Compare Strings:

Swift provide three ways to compare string

  1. string equality
  2. prefix equality
  3. suffix equality

var firstString = “We are same”
var secondString = “We are same”

if firstString = secondString
{
    println(“Both strings are same”)
}

To check prefix we can use

if firstString.hasPrefix(“We”)
{
    println(“First string contains we”)
}

To check suffix we can use

if secondString.hasSuffix(“same”)
{
    println(“Second string contains same”)
}


 UPPERCASE and lowercase :

We can convert string to both in uppercase and lowercase by using property uppercaseString and lowercaseString

let string = ” normal”

let resultedString = string.uppercaseString
println(“result uppercase=(resultedString) )

resultedString = string.lowercaseString
println(“result lowercase=(resultedString) )