Swift 数组和字符串转换基础

数组转字符串

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.. Bool) rethrows -> Int?
func lastIndex(where predicate: (Element) throws -> Bool) rethrows -> Int?
方法三:
let con = dataArray.contains(where: {$0 == "小雨"})
debugPrint(con)
输出结果:true

//注意:该方法主要是用来判断数组中是否包含符合某个条件的对象,返回值为true或false

你可能感兴趣的:(Swift 数组和字符串转换基础)