加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

Swift2.0学习二

发布时间:2020-12-14 06:46:57 所属栏目:百科 来源:网络整理
导读:Swift2.0学习二 可选型 在Swift中 nil 本身是一种特殊的类型。 解包 if let errorCode = errorCode { print(errorCode)}else {} Optional Chaining 和 Nil-Coalesce let message2 = errorMessage == nil ? "No error" : errorMessagelet message3 = errorMes

Swift2.0学习二

可选型

在Swift中nil本身是一种特殊的类型。

解包

if  let errorCode = errorCode  {
    print(errorCode)
}else {

}

Optional Chaining 和 Nil-Coalesce

let message2 = errorMessage == nil ? "No error" : errorMessage
let message3 = errorMessage ?? "No Error"

如果为nil则设置一个默认值"No Error"

可选项在元组中使用

var error1: (errorCode: Int,errorMessage: String?) = (404,"Not Found")
error1.errorMessage
error1 = nil //出错

var error2: (errorCode: Int,errorMessage: String)? = (404,"Not Found")
error2.errorMessage = nil //出错
error2 = nil

隐式可选型
隐式可选型可以存放nil,但在使用的时候,可以不用解包

var errorMessage: String! = nil
errorMessage = "Not  found"
"The message is " + errorMessage

在使用的时候必须保证有值,否则会出错。

Collections

数组

数组初始化

var numbers: [Int] = [0,1,2,3,4,5]
var vowels: [String] = ["A","E","I","O","U"]

或者

var numbers: Array<Int> = [0,5]

声明空数组

var emptyArray1: [Int] = []
var emptyArray2 = [Int]()

或者,使用初始化,初始化为同一个值

var allZeros = [Int](count:5,repeatedValue:0)

获取第一个和最后一个值,返回值为可选型vowels.firstvowels.last
numbers.minElement()numbers.maxElement()获取最小和最大的元素

数组的遍历

for number in numbers {

}

或者同时得到索引值和元素的内容

for (index,number) in numbers.enumerate() {
    print("(index+1) : (number)")
}

NSArray
var array1 = [1,3] as NSArray数组转为NSArray
NSArray中可以存放各种不同的数据类型
NSArray是一个类,而Swift中的数组是一种结构

字典

声明一个字典

var dict: [String: String] = ["Swift":"雨燕","python":"大蟒"]
var dict2: Dictionary<String,String> = ["Swift":"雨燕","python":"大蟒"]

声明一个空字典

var emptyDictionary1: [String:Int] = [:]
var emptyDictionary2: Dictionary<Int,String> = [:]
var emptyDictionary3 = [String:String] ()
var emptyDictionary4 = Dictionary<Int,Int> ( )

使用一个键访问一个字典返回时一个可选型
获取所有的键和所有的值

Array(dict.keys)
Array(dict.values)

遍历字典

for (key,value) in dict {
    print("(key):(value)")
}

字典操作
更新value

dict.updateValue("Swift",forKey: "Swift")

updateValue会将旧的值给返回过来

删除

dict["Swift"] = nil
dict.removeValueForKey("Swift")//有返回值

集合

声明一个集合

var skillsOfA: Set<String> = ["swift","OC"]
var vowels = Set(["A","U"])

声明一个空的集合

var emptySet1: Set<Int> = []
var emptySet2 = Set<Double> ()

函数

无返回值,如下几种表现形式

func printHello() {
    print("Hello")
}
func printHello1() -> Void {
    print("Hello")
}
func printHello2() -> () {
    print("Hello")
}

省略外部参数名

func mutiply(num1: Int,_ num2: Int) -> Int {
    return num1 * num2
}
mutiply(4,2)

给参数设置默认参数值

func sayHelloTo(name name: String,withGreetingWord greeting: String = "Hello") -> String {
    return "(greeting),(name) !"
}

变长参数类型
对一个函数来说,最多只有一个变长的类型

func mean( numbers: Double ... ) -> Double {
    var sum: Double = 0

    for number in numbers {
        sum += number
    }
    return sum / Double(numbers.count)
}

mean(2)
mean(2,3)
mean(2,4)

常量参数 变量参数和inout参数
如下的例子

func toBinary( num: Int ) -> String {
    var res = ""
    repeat{
        res = String(num%2) + res
        num /= 2 //报错 默认情况下参数都是一个常量类型,不能改变
    }while num != 0
    return res
}

如下所示,交换两个数,但是实际上并没有改变

func swapTwoInts(var a: Int,var _ b: Int) {
    let t: Int = a
    a = b
    b = t
}

var x: Int = 1
var y: Int = 2
swapTwoInts(x,y)
x//1
y//2

如何处理呢?

func swapTwoInts(inout a: Int,inout _ b: Int) {
    let t: Int = a
    a = b
    b = t
}

var x: Int = 1
var y: Int = 2
swapTwoInts(&x,&y)
x//2
y//1

函数类型
将函数作为变量

func add( a: Int,_ b: Int ) -> Int {
    return a + b
}
let anotherAdd: (Int,Int) -> Int = add
anotherAdd(3,4)

返回值为空可以这样表示,去掉参数的括号也行

func sayHelloTo(name: String) {
    print("Hello,(name)!")
}
let anotherSayHelloTo: (String)->() = sayHelloTo

如果参数和返回值都为空 ()->()()->VoidVoid->()Void->Void都可

用法,例如排序

func biggerNumberFirst( a: Int,_ b: Int ) -> Bool{
    if a >  b {
        return true
    } else {
        return false
    }
}

arr.sort(biggerNumberFirst)

函数式编程
map函数,最数组中每一元素,做出改变

func changeScores( inout scores: [Int],by changeScore: (Int) -> Int ) {
    for ( index,score ) in scores.enumerate() {
        scores[index] = changeScore(score)
    }
}


func changeScore1( score: Int ) -> Int {
    return Int(sqrt(Double(score)) * 10)
}


var score1 = [36,61,78,89,100]
print(score1)
changeScores(&score1,by: changeScore1)
score1

score1.map(changeScore1)
score1

filter对数组过滤,过滤出适合的数据

func fail(score: Int) -> Bool {
    return score < 60
}
score1.filter(fail)
score1

reduce对数组求和

var score = [1,4]
func add(num1: Int,_ num2: Int) -> Int {
    return num1 + num2
}
score.reduce(0,combine: add)
score.reduce(0,combine: +)

闭包

闭包的基本语法

arr.sort { (a: Int,b: Int) -> Bool in
    return a > b
}

闭包的简化

arr.sort { (a: Int,b: Int) -> Bool in return a > b }
arr.sort({ a,b in return a > b})
arr.sort({ a,b in a > b})
arr.sort( { $0 > $1} )
arr.sort(>)//>本身就是一个函数

结尾闭包(Trailing Closure)
当闭包是一个函数的最后一个参数时,可以把闭包放在外面,甚至去掉括号。如下:

arr.sort(){a,b in return a > b }
arr.sort{a,b in return a > b }
arr.map{ (var number) -> String in
    var res = ""
    repeat{
        res = String(number%2) + res
        number /= 2
    }while number != 0
    return res
}

内容捕获
捕获{}外面的变量

var num = 700
arr.sort{ a,b in
    abs(a-num) < abs(b-num)
}

闭包和函数是引用类型

func runningMetersWithMetersPerDay( metersPerDay: Int ) -> ( ) -> Int {
    var totalMeters = 0
    return {
        totalMeters += metersPerDay
        return totalMeters
    }
}

var planA = runningMetersWithMetersPerDay(2000)
planA()//2000
planA()//4000

var planB = runningMetersWithMetersPerDay(5000)
planB()//5000
planB()//10000

var anotherPlan = planB
anotherPlan()//15000

planB()//20000

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读