Swift Array的高级使用

前端之家收集整理的这篇文章主要介绍了Swift Array的高级使用前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

开发过程中使用数组的概率非常高,这里对部分功能做一个介绍,使用playground去显示,打印出来的内容我就不一一写上去了,真的很有用!

//: Playground - noun: a place where people can play

import UIKit


//数组问题
struct student {
    var name = "123"
    
}

var str = "Hello,playground"

//将多个数组合成一个数组
let array = [[1,2,4,],[3,5],[565,33]]
//let arrayMap = array.map{$0}
let arrayFlat = [[123,123],[444]].flatMap{ $0 }
print(arrayFlat)

//分离出条件内的数字并和成数组
let arrayFilter = [1,3,5,6,20]
let tempFilter = arrayFilter.filter{ $0 % 2 == 0 }
print(tempFilter)

//获取数组的和
let sumArray = [2,7]
let tempSum = sumArray.reduce(0){ $0 + $1}
print(tempSum)

//从类里面遍历出来
var oneS = student.init()
oneS.name = "1"
var oneS1 = student.init()
oneS1.name = "2"
var oneS2 = student.init()
oneS2.name = "3"
let students = [oneS,oneS1,oneS2]
let endS = students.filter { (student) -> Bool in
    return student.name == "2"
}
if let endA = endS.last {
    print(endS.last)
}

//取出空数组
let nilArray = [[],[23,322],[4,4],[],[666,777],[]]
let tempNilArray = nilArray.filter { (array) -> Bool in
    return array.count > 0
}
print(tempNilArray)

//forEach遍历数据
let testArrA = [1,1]
let testArrB = [1,5]
let testArrC = ["a","b","c","D"]
(2..<testArrA.count).forEach { (countT) in
    print(countT)
}

//遍历
testArrC.enumerated().forEach { (oneStr) in
    print(oneStr.element)
}

//从某一点这个点开是,分离成两个数组,并去掉当前的元素
testArrA.split(separator: 4)
testArrC.split(separator: "b")
//条件分离
testArrA.split { (tempInt) -> Bool in
    return tempInt <= 1
}

//删除索引之前的对象
testArrC.dropFirst(0)
testArrC.dropLast(1)

//修改数组元素内容
print(testArrC.map{$0.lowercased()})

//排序
print(testArrC.sorted(by: < ))
print(testArrB.sorted(by: < ))

//倒序
print(Array(testArrA.reversed()))

//prefix,取前几位的值
print(testArrA.prefix(3))

//suffix,取后几位的值
print(testArrA.suffix(1))

// 运算符重载
func == (stu1: student,stu2: student) -> Bool {
    if stu1.name == stu2.name {
        return true
    }
    return false
}

let isEqual = oneS1 == oneS
let threeArr = [1] + [3] + [1,88]

let befor = 1
let later = ~1
print(later)

//枚举
enum WeekType {
    case One
    case Two
}
如果转载请注明转于: AirZilong的博客 原文链接:https://www.f2er.com/swift/322197.html

猜你在找的Swift相关文章