iOS Programming (1) – All about Swift

What’s optionals?

Value of a variable is optional, it can be nil or not nil

Define a variable

var test: String?    // test can be a string or nil

// This initialization is acceptable
var test01: String? = nil       // test01 is "optional" type so it's ok to set it as "nil"

// This initialization is error
var test02: String = nil         // test02 is "String" type so you can't set it as "nil"

Unwrap optionals

var test01: String? = nil       // test01 is "optional type"
test01 = "hung"

// Not unwrap yet
var test02 = test01
print(test02) // Optional "hung"

// Unwrap
var test03 = test01!
print(test03) // String "hung"

Safety check

var test01: String? = nil       // test01 is "optional type"

// Unwrap ERROR
print(test01!)  // Error, app crashes because you are printing nil (nothing)

// Safety check
if (test01 != nil) {
    print(test01!)
}
if let roomCount = john.residence?.numberOfRooms {
    print("John's residence has \(roomCount) room(s).")
} else {
    print("Unable to retrieve the number of rooms.")
}

How to write inline conditional?

let fileExists = false
println("something " + (fileExists ? "exists" : "does not exist"))
// output: "something does not exist"

How to deal with string?

How to do Case Insensitive Comparison?

let valueExpected = "SUCCESS"
let valueProvided = "success"
        
if valueExpected.caseInsensitiveCompare(valueProvided) == ComparisonResult.orderedSame
{
    print("Strings are equal")
}

How to display a Toast text?

DispatchQueue.main.async {
    self.view.makeToast("Some text here")
}

How to deal with Collection?

How to remove first element?

.removeFirst()

How to remove an object?

if let index = arrItems.index(where: {$0 as! AnObjectType == AnObjectType.age}) {
    arrItems.remove(at: index)
}

Be the first to comment

Leave a Reply

Your email address will not be published.


*