As vadian said on his answer
You cannot assign a value to index 0 because there is no index 0 if
the array is empty.
You have to append or insert the item:
arrayLocations.append([27.1750199, 78.0399665])
I suggest that you make use of this Collection
extension so that your code won't crash often
extension Collection where Indices.Iterator.Element == Index {
/// Returns the element at the specified index if it is within bounds, otherwise nil.
subscript (safe index: Index) -> Generator.Element? {
return indices.contains(index) ? self[index] : nil
}
}
By using this you could just use if let
blocks
Sample:
if let aLocation = arrayLocations[safe: 0] {
aLocation = [27.1750199, 78.0399665]
}
This ensures that even if you try to access an object of index 0
your code won't crash.
Suggestion:
Note: This suggestion is not part of the answer, but rather something to improve your code.
It looks like you're trying to create an array of latitude and longitude. Using an array for the latitude and longitude
object isn't very wise. I suggest that you create an object instead, it can be a struct
or a typeAlias
For example:
struct CoordinateStruct {
var longitude: Float
var latitude: Float
}
/* or */
typealias CoordinateTypeAlias = (latitude: Float, longitude: Float)
/************************* */
// Your code would then look like this
var arrayLocations:[CoordinateStruct] = []
arrayLocations.append(CoordinateStruct(longitude: 27.12312312, latitude: 78.123123))
/* or */
var arrayLocations:[CoordinateTypeAlias] = []
arrayLocations.append((27.12312312, 78.123123))
// Which would make accessing them very easy and readable, like this.
if let aLocation = arrayLocations[safe: 0] {
print(aLocation.longitude)
print(aLocation.latitude)
// instead of this
print(aLocation[0]) // a person who reads your code won't understand this
print(aLocation[1]) // a person who reads your code won't understand this
}