Swift2.0学习二
Swift2.0学习二可选型在Swift中 解包 if let errorCode = errorCode { print(errorCode) }else { } Optional Chaining 和 Nil-Coalesce let message2 = errorMessage == nil ? "No error" : errorMessage let message3 = errorMessage ?? "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 隐式可选型 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) 获取第一个和最后一个值,返回值为可选型 数组的遍历 for number in numbers { } 或者同时得到索引值和元素的内容 for (index,number) in numbers.enumerate() { print("(index+1) : (number)") } NSArray 字典声明一个字典 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)") } 字典操作 dict.updateValue("Swift",forKey: "Swift")
删除 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 如果参数和返回值都为空 用法,例如排序 func biggerNumberFirst( a: Int,_ b: Int ) -> Bool{ if a > b { return true } else { return false } } arr.sort(biggerNumberFirst) 函数式编程 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
func fail(score: Int) -> Bool { return score < 60 } score1.filter(fail) score1
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 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |