字符串和数组转换
func aryChangeStr() {
let ary = ["1","3","4","hello","word"]
let aryStr = ary.joined()
print("数组转字符:\(aryStr)")//134helloword
let aryStr2 = ary.joined(separator: "-")
print("数组转字符以-分割:\(aryStr2)")//1-3-4-hello-word
}
func strChangeAry() {
let str = "helloSwift"
let strAry = Array(str)
let strAry2 = str.compactMap { (item) -> String? in
return "\(item)"
}
print("字符串转数组1:\(strAry)数组2:\(strAry2)")
//["h", "e", "l", "l", "o", "S", "w", "i", "f", "t"]
//["h", "e", "l", "l", "o", "S", "w", "i", "f", "t"]
let str1 = "足球,,篮 球,乒乓球, 羽毛球, ,"
let strAry3 = str1.split(separator: ",")
let strAry4 = str1.components(separatedBy: ",")
print("字符串转数组有分割字符,1:\(strAry3)数组2:\(strAry4)")
//1,["足球", "篮 球", "乒乓球", " 羽毛球", " "]
//2,["足球", "", "篮 球", "乒乓球", " 羽毛球", " ", ""]
//在使用分隔符来分割字符串时,方法一与方法二的区别在于,
//如果存在两个相邻的分隔符,
//方法二会留存空字符串,方法一则会去掉空字符串。
}
//MARK: 遍历数组
func aryEach() {
let ary = ["晴天","阴天","大雨","多云","大风","雨夹雪","小雨"]
ary.forEach { (item) in
print("数组遍历forEach:\(item)")
}
//for item in 比forEach省时
for item in ary {
print("数组遍历for item in :\(item)")
}
/// 该循环方式可设置开闭区间,设置时需注意数组越界
for idx in 0.. String? in
// return "\(item)"
// }
print("过滤掉nil后的Ary2:\(filterAry2)")
let filterAry3: [Any] = ary2.compactMap { (item) in
let itemStr: String = item as? String ?? ""
if itemStr.contains("雨"){
return item
}
return nil
}
print("过滤到不包含雨的:\(filterAry3)")//["大雨", "雨夹雪", "小雨"]
let filterAry4 = ary2.filter { (item) -> Bool in
let itemStr: String = item as? String ?? ""
return itemStr.contains("雨")
}
print("过滤到不包含雨的:\(filterAry4)")
//[Optional("大雨"), Optional("雨夹雪"), Optional("小雨")]
}
数组查询
func searchAry() {
////注意:该方法是从数组的第一个位置开始查找,当有符合条件的对象就输出,剩下的不会继续查找。
if let text = ary.first(where: {$0.hasSuffix("雨")}) {
print("查找末尾字符是“雨”的对象:\(text)")
//查找末尾字符是“雨”的对象:大雨
}
////注意:该方法是从数组的最后一个位置开始查找,当有符合条件的对象就输出,剩下的不会继续查找。
if let text = ary.last(where: {$0.hasSuffix("雨")}) {
print("从最后一个位置查找末尾字符是“雨”的对象:\(text)")
//从最后一个位置查找末尾字符是“雨”的对象:小雨
}
//lastIndex
if let text = ary.firstIndex(where: {$0.hasSuffix("雨")}) {
print("查找末尾字符是“雨”的对象:\(text)")
//查找末尾字符是“雨”的对象:2
}
let contains = ary.contains(where: {$0 == "小"})
print(#"数组中是否有"小"这对象"#+"\(contains)")
//数组中是否有"小"这对象false
}