Tuesday, October 11, 2016

Swift 3:- For Loops, While Statements, Random Number, Casting & Dictionaries

These are formatted so you can copy the code straight into your Swift Playground files.


// would print up to 9
for i in 0 ..< 10 {
    print (i) //i will increment up one with each iteration of the for loop
}
// would print up to 10
for i in 0 ... 10 {
    print (i)
}
// iterate through an array
let names = ["Bob", "Carl", "Joe", "Dory" ]
for name in names {
    print (name)
}
// nodes in a sprite kit scene (won't work in Playgrounds)
for node in self.children {
    if (node.name == "Ball") {
        //do something
    }
}

While Statements

// The code would run this loop 100 times
var i:Int = 0
while i < 100 {
    print(i)
    i += 1 //increment i so eventually we break out of the while loop
}
// while loops can also be used with non-numbers
var title:String = ""
//this loop will run 5 times
while title != "aaaaa" {
    title = title + "a"  //add another "a" each loop to the title
}

Random Number

//  Make a variable equal to a random number....
let randomNum:UInt32 = arc4random_uniform(100) // range is 0 to 99
// convert the UInt32 to some other  types
let randomTime:TimeInterval = TimeInterval(randomNum)
let someInt:Int = Int(randomNum)
let someString:String = String(randomNum) //string works too

Casting
Dictionaries

//create the Swift 3 Dictionary with nothing, and set the types 
// (String will be Key, and any object will be the value
var someDict = [String : AnyObject]()
// add a key and value
someDict["Ex wives"] = 5
print (someDict)
// add another key and value
someDict["Current wives"] = 1
print (someDict)
//remove Current wives. Oh well.
someDict.removeValue(forKey: "Current wives")
print (someDict)
//changes ex wives to 6
someDict["Ex wives"] = 6
print (someDict)
// remove all
someDict.removeAll()

No comments:

Post a Comment