Swift 5: Index of a Character in String

后端 未结 1 425
你的背包
你的背包 2021-01-05 03:00

Before Swift 5, I had this extension working:

  fileprivate extension String {
        func indexOf(char: Character) -> Int? {
            return firstI         


        
相关标签:
1条回答
  • 2021-01-05 03:39

    After some time I have to admit that my original answer was incorrect.

    In Swift are two methods: firstIndex(of:) and lastIndex(of:)

    Both returns Int? representing index of first/last element in Array which is equal to passed element (if there is any, otherwise it returns nil).

    So, you should avoid using your custom method to get index because there could be two same elements and you wouldn't know which index you need. So try to thing about your usage and decide which index is more suitable for you; first or last.

    0 讨论(0)
提交回复
热议问题