Swift access element of an Array


import UIKit

let weekDays:[String] = [
    "Sunday",
    "Monday",
    "Tuesday",
    "Wednesday",
    "Thursday",
    "Friday",
    "Saturday"
]

let multiArray = [
    [1,"One"],
    [2,"Two"],
    [3,"Three"],
    [4,"Four"],
    [5,"Five"]
]

let emptyArray: [String] = []

var result: String;
var myArray: [Any];

//direct access by index
result = weekDays[2]
print(result)
//Result = Tuesday

//direct access by index of multi dimensional array
myArray = multiArray[2]
print(myArray)
//Result = [3, "Three"]

result = myArray[1] as! String
print(result)
//Result = Three

//get first element
result = weekDays.first!
print(result)
//Result = Sunday

//get last element
result = weekDays.last!
print(result)
//Result = Saturday

//total number of elments in the array
let count = weekDays.count
print(count)
//Result = 7

let count2 = multiArray.count
print(count2)
//Result = 5

//is the array empty?
print(weekDays.isEmpty)
//Result = false
print(emptyArray.isEmpty)
//Result = true

//loop thru the array
weekDays.forEach{
    print($0)
}

for item in weekDays {
    print(item)
}

for (index,value) in weekDays.enumerated() {
    print("\(index) \(value)")
}

//loop thru multi dimensional array
for item in multiArray {
    item.forEach{
        print($0)
    }
}


No comments:

Post a Comment

NO JUNK, Please try to keep this clean and related to the topic at hand.
Comments are for users to ask questions, collaborate or improve on existing.