Swift get Index of matching Element in an array


import UIKit

let weekDays:[String] = [
    "Sunday",
    "Monday",
    "Tuesday",
    "Wednesday",
    "Thursday",
    "Friday",
    "Saturday",
    "Sunday",
    "Monday",
    "Tuesday",
    "Wednesday",
    "Thursday",
    "Friday",
    "Saturday"
]


let firstIndex = weekDays.firstIndex(of: "Tuesday")
print(firstIndex ?? -1)
//Result = 2

let lastIndex = weekDays.lastIndex(of: "Tuesday")
print(lastIndex ?? -1)
//Result = 9

let notFound = weekDays.firstIndex(of: "tuesday")
print(notFound ?? -1)
//Result = -1

print(weekDays.firstIndex(where: { $0.hasSuffix("day") })!)
//Result = 0

print(weekDays.firstIndex(where: { $0.hasPrefix("Wed") })!)
//Result = 3

No comments:

Post a Comment

NO JUNK, Please try to keep this clean and related to the topic at hand.
Comments are for users to ask questions, collaborate or improve on existing.