Swift Array - Check if an index exists
An elegant way in Swift:
let isIndexValid = array.indices.contains(index)
How Can I Check My Array Index is Out of Range in Swift
It would be better to use an optional extension which returns nil
if the element at the index doesn't exist.
Extension
extension Collection where Indices.Iterator.Element == Index {
subscript (optional index: Index) -> Iterator.Element? {
return indices.contains(index) ? self[index] : nil
}
}
Usage:
mannschaft18teamid = results2.data.table[optional: 17]?.team_id ?? "not existing"
Check if array contains an index value in Swift
If you're dealing with array of integers and are only worried about the first two items, you can do something like:
let items: [Int] = [42, 27]
let firstItem = items.first ?? 0
let secondItem = items.dropFirst().first ?? 0
Whether you really want to use the nil coalescing operator, ??
to make missing values evaluate to 0
, or just leave them as optionals, is up to you.
Or you could do:
let firstItem = array.count > 0 ? array[0] : 0
let secondItem = array.count > 1 ? array[1] : 0
How do I check if an array index is out of range SWIFT
Before indexing into the array, you need to check:
- The intended index is not below 0
- array's
count
is above the intended index
let intendedIndex: Int = 3
if (intendedIndex >= 0 && questions.count > intendedIndex) {
// This line will not throw index out of range:
let question3 = questions[intendedIndex]
}
SwiftUI: checking if next index exists in a ForEach
You need to iterate your collection indices and check if the index + 1 is less then the collection endIndex:
ForEach(item.currency.indices) {
Text(verbatim: item.currency[$0])
.font(Font.custom("Avenir", size: 18))
.foregroundColor(Color("47B188"))
.padding(.leading, 18)
if $0 + 1 < item.currency.endIndex {
Text("|")
}
}
How to check if an element is in an array
Swift 2, 3, 4, 5:
let elements = [1, 2, 3, 4, 5]
if elements.contains(5) {
print("yes")
}
contains()
is a protocol extension method of SequenceType
(for sequences of Equatable
elements) and not a global method as in
earlier releases.
Remarks:
- This
contains()
method requires that the sequence elements
adopt theEquatable
protocol, compare e.g. Andrews's answer. - If the sequence elements are instances of a
NSObject
subclass
then you have to overrideisEqual:
, see NSObject subclass in Swift: hash vs hashValue, isEqual vs ==. - There is another – more general –
contains()
method which does not require the elements to be equatable and takes a predicate as an
argument, see e.g. Shorthand to test if an object exists in an array for Swift?.
Swift older versions:
let elements = [1,2,3,4,5]
if contains(elements, 5) {
println("yes")
}
ios how to check if object in array in particular index exist?
It is my understanding that you cannot have an index of an array unless you have and object there. What I would suggest is to set all indexes in the array to [NSNull null]
and then in your if statement check to see if the object at that index is an NSNull object. if([[self.myArray objectAtIndex:index] isKindOfClass:[NSNull class]])
then if that returns true, have it replace the null object with your object
Check if index exists for Array of NSURL
You can find it through count
var data = [[String]]()
let data1 = ["test 1","test 2"]
data.append(data1)
let indexToFind = 1
if data[0].count > indexToFind {
print("found")
print("value \(data[0][indexToFind])")
}
else {
print("not found")
}
If indexToFind = 2 then you will get
not found
If indexToFind = 1 then you will get
found
value test 2
FOR URL
You can count characters in url by absoluteString.characters.count
var data = [[NSURL?]]()
let data1 = [NSURL(string: ""),NSURL(string: ""),NSURL(string:"http://google.com")]
data.append(data1)
let indexToFind = 2
if data[0].count > indexToFind {
print("found")
print("value \(data[0][indexToFind]!)")
if data[0][indexToFind]!.absoluteString.characters.count > 0 {
print("this is an url")
}
}
else {
print("not found")
}
OUTPUT :
found
value http://google.com
this is an url
Related Topics
How to Use Attributed String in Swiftui
How to Compare One Value Against Multiple Values - Swift
How to Round a Double to the Nearest Int in Swift
How to Apply the Type to a Nsfetchrequest Instance
Swift Dictionary Get Key For Value
Unexpected Non-Void Return Value in Void Function (Swift 2.0)
Changing the Status Bar Color For Specific Viewcontrollers Using Swift in Ios8
Uialertcontroller - Add Custom Views to Actionsheet
Whither Dispatch_Once in Swift 3
How to Declare an Array of Weak References in Swift
Dynamically Hiding View in Swiftui
How Does One Generate a Random Number in Swift
How to Deal With @Objc Inference Deprecation With #Selector() in Swift 4
Nsattributedstring, Change the Font Overall But Keep All Other Attributes