Let's suppose we have an array:
array = ["a", "b", "c"]
and I want to get the Index by knowing a value (a):
array.firstIndex(of: "a")
this then gives me 'Optional(1)', but how can I get an Integer from that?
Let's suppose we have an array:
array = ["a", "b", "c"]
and I want to get the Index by knowing a value (a):
array.firstIndex(of: "a")
this then gives me 'Optional(1)', but how can I get an Integer from that?
guard let index = array.firstIndex(of: "a") else { return }
print(index)
or
if let index = array.firstIndex(of: "a") {
print(index)
}
firstIndex()
returns a value of type Int?
, so like any other optional type you will have to unwrap it somehow.
The developer docs (https://developer.apple.com/documentation/swift/optional) list a few different ways to do just that. Without knowing exactly how you want to use this value, it's hard to know which method will be best for you.
You'll need to unwrap the Optional value, or you can use a ?
to use optional chaining to reference the integer iff it's non-nil:
guard let index = array.index(of: "a") else {
...
}
...
OR
let index = array.index(of: "a")
index?.description