作为开发语言,首先我们要了解他的基本语法特性。按照惯例,就从Hello, World!开始吧! print("Hello, World!") print("hello swift") ////////////////////////////////////////////////////////////// // 1.显示指定一个常量,并且把4赋给a,常量(let)意味着你只能给它赋一次值 let a:Float = 4 let b = 5.0 let c = 7 let str = "hello swift" print(a) print(b) print(c) print(str) ////////////////////////////////////////////////////////////// // 2.使用 \() 把基本数据类型转化成字符串,字符串的拼接 let str1 = str + " "+String(c) let str2 = "hello swift \(c).0" print(str1) print(str2) ////////////////////////////////////////////////////////////// // 3.数组和字典 var shoppingList = ["book","food","water"] print(shoppingList[1]) shoppingList[1] = "pancel" print(shoppingList[1]) var occupations = ["Tank":"coder","Wade":"player"] print(occupations["Tank"]) ////////////////////////////////////////////////////////////// // 4.控制流 // 4.1 {}不能省略; // 4.2 条件必须是一个bool表达式,不是隐式的作比较,可以用if let来处理缺省值的情况,let后必须要是一个“可选值” let individualScores = [89,20,84,68,73] var teamScore = 0 for score in individualScores{ if score > 60{ teamScore += 3 } else{ teamScore += 1 } } print(teamScore) // 4.3 在类型后面用?来标记一个标示这个变量值是可选的,一个可选的值可能是一个具体的值或者nil var optionalString :String? = "Hello" print(optionalString == nil) // false var optionalName:String? = "Kobe" var greeting = "Hello!" if let name = optionalName{ greeting = greeting + "\(name)" // Hello!Kobe print(greeting) }else{ print(greeting) } // 4.4 switch语句,支持任意数据类型的各种比较,switch语句运行到匹配语句后会自动退出,故而不要每一句都加break let vegetable = "red pepper" switch vegetable{ case "celery": let vegetableComment = "Add some raisins and make ants on a log" print(vegetableComment) case "cucumber","watercress": let vegetableComment = "That would make a good tea sandwich." print(vegetableComment) // 申明let可以用于匹配某部分固定值的模式 case let x where x.hasSuffix("pepper"): let vegetableComment = "Is it a spicy \(x)?" print(vegetableComment) default: let vegetableConnent = "Everything tastes good in soup." print(vegetableConnent) } ////////////////////////////////////////////////////////////// // 5.for in 遍历字典,获取 键 && 值 let interestingNumbers = ["Prime":[2,3,5,7,11,13],"Fabomacci":[1,1,2,3,5,8],"Square":[1,4,9,16,25]] var largest = 0 var type = "" for(kind,numbers) in interestingNumbers{ for number in numbers{ if number > largest{ largest = number type = kind } } } print(largest) // 25 print(type) //Square ////////////////////////////////////////////////////////////// // 6.for语法 ... var firstForLoop = 0 var secondForLoop = 0 // 6.1 传统写法 for var i=0;i<4;++i{ firstForLoop = firstForLoop + i } print(firstForLoop) // 6.2 新写法 ... / ..< for i in 0...4{ secondForLoop = secondForLoop + i } print(secondForLoop) ////////////////////////////////////////////////////////////////////////////////////// // 7.函数和闭包(block):①.用func来定义一个函数 ②.用名字和参数调用函数 ③.用 -> 来指定函数返回值 // 7.1 函数返回一个值 func greeting(name:String,day:String)->String{ return "hello \(name) , today is \(day)" } print(greeting("tank",day: "september 1")) // hello tank , today is september 1 (day: 不能省略) // 7.2 函数返回多个值 : 使用元组让一个函数返回多个值,该元组的元素可以用名称或者数组表示 func calculateStatistics(scores:[Int])->(min:Int,max:Int,sum:Int){ var min = scores[0] var max = scores[0] var sum = 0 for score in scores{ if score > max{ max = score } if score < min{ min = score } sum += score } return (min,max,sum) } let statistics = calculateStatistics([1,2,3,4,5,6,7,8,9,10]) print(statistics) // (1, 10, 55) ---> 不是数组哦 print(statistics.1) // 10 print(statistics.sum) // 55 print([1,2,3,4,5,6,7,8,9,10]) // [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] // 7.3 函数可以带有可变个参数,这些参数在函数内表现为数组形式 func sumOf(numbers:Int...)->Int{ var sum = 0 for number in numbers{ sum += number } return sum } let sum = sumOf(1,2,3,4) // sumOf([1,2,3,4]) ERROR print(sum) // 10 // 7.4 函数可以被嵌套,被嵌套的函数可以访问外层函数的变量,可以试用嵌套来重构一个“太复杂”或者“太长”的函数 func returnFifteen()->Int{ var y = 10 func add(){ y = y+5 } add() return y } print(returnFifteen()) // 15 // 7.5 函数可以作为另一个函数的返回值 (Int->Int)------>表示返回值是一个函数,这个函数传入一个int返回值是int func makeIncrementer()->(Int->Int){ func addOne(number:Int)->Int{ return number+1 } return addOne // 注意这里add不带参数 } var increament = makeIncrementer() print(increament(7)) // 8 // 7.6 函数作为参数传入另一个函数 func hasAnyMatches(list:[Int],condition:Int->Bool)->Bool{ for item in list{ if condition(item) { return true } } return false } func lessThanTen(number:Int)->Bool{ if number < 10{ return true } return false } /************作为参数传入或者返回时,只要写函数名即可,不需要带参数****************/ print(hasAnyMatches([1,2,3,4,5,6], condition:lessThanTen)) // true print(hasAnyMatches([11,12,13,14], condition: lessThanTen)) // false // 7.7 函数是一种特殊的闭包,可以试用{}来创建一个匿名的闭包。使用in将参数和返回值类型声明与闭包函数体进行分离 // map函数 ---> 建立一个映射 y = f(x) var numbers = [20,19,7,2] var tripleNumbers = numbers.map({(number : Int)->Int in let result = 3*number return result }) var oddsToZero = numbers.map({(number:Int)->Int in if number%2 == 0{ return number }else{ return 0 } }) print(tripleNumbers) // [60, 57, 21, 6] print(oddsToZero) // [20, 0, 0, 2] ////////////////////////////////////////////////////////////// // 8.对象和类 // 8.1 创建一个类,构造器(析构函数) class Shape{ var numberOfSides = 0 var name:String var sideLength : Double = 0.0 init(sideLength:Double, name:String){ self.sideLength = sideLength self.name = name } var perimetre:Double{ get{ return 3*sideLength } set{ sideLength = newValue/3 } } func simpleDesctiption()->NSString{ return "\(name) with \(numberOfSides) sides." } func simpleDesctiption(num:Int)->NSString{ return "a shape with \(num) sides." } } // 8.2 创建一个类的实例,在类名后面加入一个括号 var shape = Shape(sideLength:12,name:"Triangle") shape.numberOfSides = 3 print(shape.simpleDesctiption()) // a shape with 7 sides. print(shape.simpleDesctiption(8)) // a shape with 8 sides. ////////////////////////////////////////////////////////////// // 9.枚举和结构体 // 9.1 使用enum来创建枚举,枚举可以包含方法 enum Rank:Int{ case Ace = 1 case Two,Three,Four,Five,Six,Seven,Eight,Nine,Ten case Jack,Queen,King func simpleDescription()->String{ switch self{ case.Ace :return "ace" case.Jack :return "Jack" case.Queen :return "Queen" case.King :return "King" default :return String(self.rawValue) } } } let ace = Rank.Ace let aceRawValue = ace.rawValue