arr.index(of:)

available only when Element conforms to Identifiable.

// 2022.02.15

// ๐ŸŒ€Array + .index(of:)
extension Array where Element: Identifiable {
    /// find index of element in array.
    /// (available when `Element` comforms to `Identifiable`)
    /// ```
    /// array.index(of: element)    // could be nil
    /// ```
    public func index(of element: Element) -> Int? {
        for i in 0..<count {
            // โญ ๆณจๆ„๏ผš้€™่ฃกๆœ‰็”จๅˆฐ Int-based index
            //    ๆ‰€ไปฅ่ฆ็”จ Array ่€Œไธๆ˜ฏ Collection
            //    ้™ค้ž่ฆๆ”น็‚บ๏ผš
            //       extension Collection 
            //         where Self.Index == Int, Element: Identifiable
            if self[i].id == element.id { return i }
        }
        return nil
    }
}

  • ้›–็„ถไธŠ้ข็š„ extension ไนŸๅฏไปฅ็”จไธ‹้ข็š„่ชžๆณ•ไพ†ไปฃๆ›ฟ๏ผš

array.firstIndex { $0.id == element.id }
  • ไฝ†ๅฆ‚ๆžœๅœจๆ‰พไธ€ๅ€‹ใ€Œไธ€ๅฎšๅฏๆ‰พๅˆฐๅˆๅ”ฏไธ€ใ€็š„ๆฑ่ฅฟๆ™‚๏ผŒ็”จ extension ็š„่ชžๆณ•ๆœƒ่ผƒ็ฐกๆฝ”๏ผš

let i = array.index(of: element)!

ๆณจๆ„๏ผšๆˆ‘ๅ€‘ๅœจ index(of:) ๅพŒ้ขๅŠ ไธ€ๅ€‹ใ€Œ๏ผใ€๏ผŒ่กจ็คบๆˆ‘ๅ€‘็ขบๅฎš้€™ๆ˜ฏไธ€ๅ€‹ๅฏไปฅ็ต•ๅฐๆ‰พๅˆฐ็š„ๆฑ่ฅฟ๏ผŒๅŒๆ™‚ๅˆๆฒ’ๆœ‰ๅฟฝ็•ฅ้€™ๅ€‹ๅ‡ฝๆ•ธๅ›žๅ‚ณ็š„ๅ…ถๅฏฆๆ˜ฏไธ€ๅ€‹ Optinal<Int>ใ€‚

Last updated