//: FROM  https://www.anuomob.com

import UIKit
func firstIndex(of valueToFind:String,in array:[String])->Int?{
    for (index,value) in array.enumerated(){
        if value==valueToFind{
            return index
        }
    }
    return nil
}


let names = ["zhangsan","lisi","wangzwu"]
print(firstIndex(of: "lisi", in: names))

通常,我们判断==的的时候没有遇到泛型。。是如上判断

//: FROM  https://www.anuomob.com

import UIKit
func firstIndex<T:Equatable>(of valueToFind:T,in array:[T])->Int?{
    for (index,value) in array.enumerated(){
        if value==valueToFind{
            return index
        }
    }
    return nil
}

let names = ["zhangsan","lisi","wangzwu"]
print(firstIndex(of: "lisi", in: names))

需要注意的是需要添加约束T:Equatable

否则它不一定支持==

09-14 11:05