iOS - 从数组中获取第一个非空字符串元素

And*_*rew 1 arrays ios swift

我有阵列:

let array = ["", "Therapeutic Dentistry","Surgical Dentistry","Orthopedic Dentistry","Orthodontics","Genaral Medical Questions","Children Therapeutic Dentistry","Children Surgical Dentistry"]
Run Code Online (Sandbox Code Playgroud)

我想要第一个,它是空的,我怎么能从数组中获取这个元素?

Rak*_*tri 8

数组有一个first属性,如果它存在,它会为你提供第一个元素.

if let firstElement = array.first {
    print(firstElement)
}
Run Code Online (Sandbox Code Playgroud)

如果你想要第一个不是空字符串的元素,那么你可以使用 first(where:)

if let firstElement = arr.first(where: { $0 != "" }) {
    print(firstElement)
}
Run Code Online (Sandbox Code Playgroud)

编辑:

问题标题是"iOS如何从数组Swift中获取第一个元素",这就是为什么答案有两个部分.