Home > Mobile >  Get last element of an Array?
Get last element of an Array?

Time:04-08

How can I fetch the last element of an array?

I have an array of string elements as well as Int, but I don't know how to fetch last element of an array.

My array is as follows:

var nums = [ 2, 4, 6, 8, 10 ]

CodePudding user response:

The safest way to update the last element of an array is to pop it and append the new value

var nums = [ 2, 4, 6, 8, 10 ]
if nums.isEmpty { return } 
nums.popLast()
nums.append(12)

If it’s guaranteed that the array is not empty you can also use removeLast which returns a non-optional.

CodePudding user response:

let lastNumber = nums.last

last property will give you the last parameter of an array.

CodePudding user response:

In swift

To fetch the last element use nums.last .

To update the last element use nums[nums.count-1] = new_value.

CodePudding user response:

There are multiple ways you can achieve the last element of an array such as following :

var nums = [ 2, 4, 6, 8, 10 ]
if let lastElement = nums.last {
    print("Last Element : \(lastElement)")
}
 
  • Related