How to find index of list item in Swift?

后端 未结 22 1626
离开以前
离开以前 2020-11-22 06:17

I am trying to find an item index by searching a list. Does anybody know how to do that?

I see there is list.StartIndex and <

22条回答
  •  不思量自难忘°
    2020-11-22 06:43

    For (>= swift 4.0)

    It's rather very simple. Consider the following Array object.

    var names: [String] = ["jack", "rose", "jill"]
    

    In order to obtain the index of the element rose, all you have to do is:

    names.index(of: "rose") // returns 1
    

    Note:

    • Array.index(of:) returns an Optional.

    • nil implies that the element isn't present in the array.

    • You might want to force-unwrap the returned value or use an if-let to get around the optional.

提交回复
热议问题