2

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?

GDog
  • 117
  • 1
  • 8
  • It's an optional. So unwrap it. e.g. `if let index = array.firstIndex(of: "a") { ... }`. Or use `guard let` syntax. You'll really want to invest a little time getting up to speed on optionals in Swift as they're an essential part of the language. See [Optionals](https://docs.swift.org/swift-book/LanguageGuide/TheBasics.html#ID330) discussion in _The Swift Programming Language._ – Rob Sep 20 '18 at 21:56

3 Answers3

4
guard let index = array.firstIndex(of: "a") else { return }
print(index)

or

if let index = array.firstIndex(of: "a") {
    print(index)
}
Kane Cheshire
  • 1,654
  • 17
  • 20
1

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.

Ben P.
  • 52,661
  • 6
  • 95
  • 123
0

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
tokan_one
  • 899
  • 7
  • 14
  • `if let` is also another great solution if you have a section of code you only want to have ran if the value exists. I personally prefer using `guard` since it's more explicit in its intention – tokan_one Sep 20 '18 at 22:00