iOS Swift Array Example

Swift array can only store same data type values. When you declare a swift array, you had better specify the array element data type at declaration time. But if you do not specify the array element data type when declare it, it can be analyzed by the assigned data value type. And when you want to use it, you should initialize the array value first, otherwise there will throw an error. This article will show you how to create, initialize swift array, it will also show you how to add, append, edit, get, insert and remove swift array element.

1. Create & Initialize Swift Array.

1.1 Standard Array Object Declare Method.

Below is the standard way to declare and initialize an empty string array object.

// declare an empty string array list object.
var strList = Array<String>()

print("strList = \(strList)")

// declare another empty string array.
var strList2 = [String]()

print("strList2 = \(strList2)")

Below is above code execution result.

strList = []

strList2 = []

1.2 Initialize Array Value When Declare Array Object.

In below example, the array element data type is not specified when declare it, the data type will be calculated by the assigned value.

// declare an array variable and initialize it with default value.
var floatList = [1.0,12,16]

print(floatList)

Below is the result. Because the first element is float type, so the array element data type is float.

[1.0, 12.0, 16.0]

1.3 Declare Array Object, Then Initialize It Before Use It.

// declare a String data type array object.
var strList1:[String]

// assign the array values. 
strList1 = ["swift", "ios"]

print(strList1)

Below is the result.

["swift", "ios"]

1.4 Wrong Usage Of Swift Array.

  1. Use an empty array variable without specify array data type.
    // declare an empty array but do not specify the array element data type.
    var intArray = []
    
    // invoke above array variable's method will throw error Empty collection literal requires an explicit type
    intArray.append(1)

    Below is the correct usage.

    var intArray:[Int] = []
    
    intArray.append(1)
    
    print(intArray)
  2. Use an array variable which is not initialized.
    If do not assign value to array variable before use it, then it will throw variable ‘var_name’ used before being initialized error like below.

    var strList1:[String]
    
    // comment below code then the array do not has initial value.
    // strList1 = ["swift", "ios"]
    
    print(strList1)
    

    Below is the error message.

    error: HelloWorldPlayground.playground:89:7: error: variable 'strList1' used before being initialized
    print(strList1)
          ^
    
    HelloWorldPlayground.playground:85:5: note: variable defined here
    var strList1:[String]
        ^

1.5 Initialize Array Variable Use Array Initializer.

init(repeating:count:) : This array initializer will create a new array object which has count sized repeating values.

var intArr = [Int](repeating:6, count:6)

print(intArr)

Above code will get below result.

[6, 6, 6, 6, 6, 6]

2. Get Array Element Value.

2.1 Get Array Element By Index.

var strArr = ["iOS", "swift", "Xcode"]

var ele1 = strArr[0]

var ele2 = strArr[1]

print(ele1)

print(ele2)

Below is the code execution result.

iOS
swift

2.2 Get Array Element Count.

var strArr = ["iOS", "swift", "Xcode"]

// the array's count property will return the array element size.
var count = strArr.count

print("strArr has \(count) elements.")

Below is the execution result.

strArr has 3 elements.

2.3 Check Whether Array Is Empty Or Not.

Use below two methods to check whether an array is empty or not.

var strArr = ["iOS", "swift", "Xcode"]

var count = strArr.count

// use array element size to check whether array is empty.
if(count==0)
{
    print("strArr is empty.")
}else{
    print("strArr is not empty.")
}

var strArr1:[String] = []

var empty:Bool = strArr1.isEmpty

// use array's isEmpty property to check whether array is empty.
if(empty)
{
    print("strArr1 is empty.")
}else{
    print("strArr1 is not empty.")
}

Below is above code execution result.

strArr is not empty.
strArr1 is empty.

3. Iterate Array Elements.

var strArr = ["iOS", "swift", "Xcode"]

for str in strArr{
    
    print("\(str)")

}

Below is the execution result.

iOS
swift
Xcode

4. Change Array Elements Value.

  1. Change single array element by index.
    var strArr = ["iOS", "swift", "Xcode"]
    
    print(strArr[1])
    
    strArr[1] = "Android"
    
    print(strArr)

    Below is the code execution result.

    swift
    ["iOS", "Android", "Xcode"]
  2. Change multiple array elements by index range.
    var strArr = ["iOS", "swift", "Xcode"]
    
    print(strArr)
    
    strArr[0...1] = ["Java","JavaScript"]
    
    print(strArr)

    Below is the code execution result.

    ["iOS", "swift", "Xcode"]
    ["Java", "JavaScript", "Xcode"]
    

5. Insert or Append Elements To Array.

Insert & append element in array.

var strArr = ["iOS", "swift"]

print(strArr)

strArr.insert("Xcode", at: 1)

strArr.append("Android")

print(strArr)

Below is the code execution result.

["iOS", "swift"]
["iOS", "Xcode", "swift", "Android"]

6. Remove Array Elements.

var strArr = ["iOS", "swift", "Xcode", "Android", "MacOS"]

print(strArr)

strArr.remove(at: 0)

print(strArr)

strArr.removeFirst()

print(strArr)

strArr.removeLast()

print(strArr)

Below is the code execution result.

["iOS", "swift", "Xcode", "Android", "MacOS"]
["swift", "Xcode", "Android", "MacOS"]
["Xcode", "Android", "MacOS"]
["Xcode", "Android"]
READ :   How To Fix Swift Error Unable To Activate Constraint With Anchors Because They Have No Common Ancestor & LayoutConstraints Unable To Simultaneously Satisfy Constraints

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.