Swift 数组和字符串转换基础
2021-07-10 本文已影响0人
AdeSon
数组转字符串
let testArr = ["1","2","3","4","5","6","7"]
// 方法一:
let resultStr = testArr.joined()
打印resultStr结果:"1234567"
// 方法二:(如果你想要的结果字符串依然包含分割符可以使用如下方法分割)
let resultStr = testArr.joined(separator: ",")
打印resultStr结果:"1,2,3,4,5,6,7"
字符串转数组
没有分隔符的字符串分割
let testString = "abcdefghijklmn"
//方法一:
let resultArr = Array(testString)
打印resultArr结果:["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n"]
// 方法二:
let resultArr2 = testString.compactMap { (item) -> String? in
return "\(item)"
}
打印resultArr2结果:["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n"]
有分隔符的字符串分割
let slipStr:String = "adcddgjfdflldkmldv"
示例以字母"d"为分割符,将字符串分割
方法一:
let slipArray = slipStr.split(separator: "d")
打印结果:["a", "c", "gjf", "fll", "kml", "v"]
方法二:
slipStr.components(separatedBy: "d")
打印结果:["a", "c", "", "gjf", "fll", "kml", "v"]
注释:在使用分隔符来分割字符串时,方法一与方法二的区别在于,如果存在两个相邻的分隔符,方法二会留存空字符串,方法一则会去掉空字符串。
数组的遍历方法简析
var dataArray:[String] = ["晴天","阴天","大雨","多云","大风","雨夹雪","小雨"]
方法一:
dataArray.forEach { (item) in
debugPrint(item)
}
方法二:
for item in dataArray {
debugPrint(item)
}
方法三:
// 该循环方式可设置开闭区间,设置时需注意数组越界
for i in 0..<dataArray.count {
debugPrint(dataArray[i])
}
方法四:
//该方法可以循环输出元组类型,包含下标index及对应的item
for (index,item) in dataArray.enumerated() {
debugPrint(index,item)
}
注释:我尝试使用方法一与方法二,分别遍历输出0~100000之间的数字,来比较耗时长短。方法一耗时0.1173100471496582,方法二耗时0.0031960010528564453,因此方法二耗时较短,故遍历数据较多时建议使用方法二。
获取数组中符合条件的某个对象
var dataArray:[String] = ["晴天","阴天","大雨","多云","大风","雨夹雪","小雨"]
//示例是查找末尾字符是“雨”的对象
方法一:
if let text = dataArray.first(where: {$0.hasSuffix("雨")}) {
debugPrint(text)
}
输出结果:"大雨"
//注意:该方法是从数组的第一个位置开始查找,当有符合条件的对象就输出,剩下的不会继续查找。
方法二:
if let text = dataArray.last(where: {$0.hasSuffix("雨")}) {
debugPrint(text)
}
输出结果:"小雨"
//注意:该方法是从数组的最后一个位置开始查找,当有符合条件的对象就输出,剩下的不会继续查找。
同理用下面两个方法获取符合条件的对象下标:
func firstIndex(where predicate: (Element) throws -> Bool) rethrows -> Int?
func lastIndex(where predicate: (Element) throws -> Bool) rethrows -> Int?
方法三:
let con = dataArray.contains(where: {$0 == "小雨"})
debugPrint(con)
输出结果:true
//注意:该方法主要是用来判断数组中是否包含符合某个条件的对象,返回值为true或false