To find the index of an element in an array in Swift, you can use the firstIndex(of:)
method provided by the Array
type.
Here's an example:
main.swift158 chars7 lines
In this example, we have an array of numbers
and we want to find the index of the element 4
. We use the firstIndex(of:)
method to search for the first occurrence of 4
in the array. If the method finds 4
, it returns an optional value that contains the index of 4
. We use optional binding (if let
) to safely unwrap the value and print the index. If the method doesn't find 4
, it returns nil
, so we print a message indicating that 4
isn't in the array.
You can also search for an element using a closure instead of a value. Here's an example:
main.swift264 chars7 lines
In this example, we have an array of names
and we want to find the index of the first name that starts with the letter "C". We use the firstIndex(where:)
method and provide a closure that checks whether a name has the prefix "C". The method searches the array and returns the index of the first name that matches the predicate. If the method doesn't find a matching name, it returns nil
, so we print a message indicating that there isn't a name starting with "C" in the array.
gistlibby LogSnag