<span style="font-size:18px;">// Playground - noun: a place where people can play import UIKit //HelloWorld var str = "Hello, playground" //常量可以改变值 var myVariable = 42 myVariable = 50 let myConstant = 42 //指定数据类型 let floatNumber : Float = 4 //使用强制转换 let label = "the label is" let width = 94 let lanelwidth = label + String(width) //使用双引号中的来转换 let apples = 3 let oranges = 5 let appleSummary = "i have (apples) apples" let orangeSummary = "i have (oranges) oranges" //自动识别数据类型加斜杠转换 let somebody = "Alice" let age = 23.5 let hellosomebody = "(somebody) is (age)" //数组的初始化以及赋值 var shoppingList = ["Alice", "Dylan"] shoppingList[1] = "Petit Alice" //字典的初始化以及赋值 var occupations = [ "male" : "Alice", "female" : "Dylan" ] occupations["male"] = "Alice.Petit" //初始化一个空的数组或者字典 let emptyArray = [String]() let emptyDictionary = [String : Float]() //初始化一个自动识别类型的字典或者数组 let emptyArray_auto = [] let emptyDictionary_auto = [:] //控制流 不能省略大括号 let indivdualScores = [75, 42, 103, 87, 12] var teamScore = 0 for score in indivdualScores { if score > 50 { teamScore += 3 } else { teamScore += 1 } } teamScore let emptyA = ["key" : "value"] emptyA //在if条件中,条件必须是bool表达式 输入一个直接score会出错的 //使用let来标记 var optionalString : String? = "Hello" optionalString == nil var optionalName : String? = "John Appleseed" var getting = "Hello" optionalName = nil if let name = optionalName { getting = "Hello, (name)" } else { getting = "hello, Alice" } //switch let vegetable = "red pepper" switch vegetable { case "celery" : let vegetableComment = "add some" case "cummber", "watercress" : let vegetableComment = "this would make a good tea" case let x where x.hasSuffix("papper"): let vegetableComment = "is it a spicy (x)" default : let vegetableComment = "everything tastes good in soup" } //碰到匹配的句子后, switch不会继续往前走 let interstingNumbers = [ "prime" : [2, 3, 4, 6], "Fibonacci" : [1, 1, 2, 3], "Square" : [1, 4, 5] ] var largest = 0 var maxtype = "" for (kind, numbers) in interstingNumbers { for number in numbers { if number > largest { largest = number maxtype = kind } } } largest maxtype //while var n = 2 while n < 100 { n = n * 2 } n var m = 2 do { m = m * 2 } while m < 100 m //while do 不会多循环一次的 他们是等价的 //...< var firstForLoop = 0 for i in 0..<4 { firstForLoop += i } firstForLoop var secondForLoop = 0 for var i = 0; i < 4; i++ { secondForLoop += i } secondForLoop var thirdForLoop = 0 for i in 0...4 { thirdForLoop += i } thirdForLoop //func func greet(name: String, day :String) ->String { return "Hello, (name), today is (day)" } greet("Alice", "Tuesday") func whateating(name : String) -> String { return "(name) eat what?" } whateating("Alice") //使用元组让一个函数返回多个值 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 staticArray = [1, 2, 3, 4, 5] calculateStatistics(staticArray) //返回值可以用点语法 单独取到 也可以用位置 calculateStatistics(staticArray).sum calculateStatistics(staticArray).0 //函数可以带有可变个数的参数 func sumOf(numbers : Int...) ->Int { var sum = 0 for number in numbers { sum += number } return sum } sumOf(1, 2) sumOf() sumOf(1, 2, 3, 4, 5) //计算参数平均值的联系 func acr(number : Int...) ->Float { var sum = 0 for num in number { sum += num } return Float(sum) / Float(number.count) } acr(1, 2, 3) acr(3, 4) //函数可以嵌套 被嵌套函数可以访问外侧函数的变量 可以嵌套函数来构成一个太长或者太复杂的函数 func returnFifteen() ->Int { var y = 10 func add() { y += 5 } add() return y } returnFifteen() //函数可以作为另一个函数的返回值 func makeIncrementer() ->(Int ->Int) { func addOne(number : Int) -> Int { return 1 + number } return addOne } var increment = makeIncrementer() increment(7) //函数可以当做参数 传入另一个函数 func hasAnymatches(list : [Int], condition : Int->Bool) -> Bool { for item in list { if condition(item) { return true } } return false } func lessThanTen(number: Int) ->Bool { return number < 10 } var numbers = [20, 19, 2, 12] hasAnymatches(numbers, lessThanTen) //函数实际上是一种特殊闭包 使用{} 来创建一个匿名的闭包 使用int将参数和返追只类型声明与闭包函数进行分离 numbers.map({ (number: Int) -> Int in if number % 2 != 0 { return 0 } return 1 }) let mappedNumbers = numbers.map ({ number in 3*number }) mappedNumbers let sortedNumbers = sorted(numbers) { $0 > $1 } //对象和类 class Shape { var numberOdSides = 0 let testGetNumber = 0 func setNumber(number : Int) { numberOdSides = number } func simpleDescription() ->String { return "A shape with (numberOdSides) sides" } } var shape = Shape() shape.setNumber(10) shape.simpleDescription() //init class NameShape { var numberOfSides : Int = 0 var name:String init(name: String, number: Int) { self.name = name self.numberOfSides = number } func simpleDescriptin() ->String { return "A (name) with (numberOfSides) sides" } } var nameShpe = NameShape(name: "Alice", number: 20) nameShpe.simpleDescriptin() //继承 class Square: NameShape { var sidelength: Double init(sidelength: Double, name: String, number: Int) { self.sidelength = sidelength super.init(name: name, number: number) } func area() -> Double { return sidelength * sidelength } override func simpleDescriptin() -> String { return "a Square with Sides of Length (sidelength)" } } //getter setter class EquilaterTrabgle: NameShape { var sideLengths:Double = 0.0 init(side: Double, name: String, number:Int) { self.sideLengths = side super.init(name: name, number: number) } var perimter: Double { get { return 3 * sideLengths } set { sideLengths = newValue / 3.0 } } override func simpleDescriptin() -> String { return "an square triagle with (sideLengths)" } } var triangle = EquilaterTrabgle(side: 3.1, name: "Alice", number: 3) triangle.perimter triangle.perimter = 9.9 triangle.sideLengths triangle.simpleDescriptin() //默认情况 方法参数名和他们在方法内部的名字一样 class counter { var count : Int = 0 func incrementBy(amount: Int, numberOfTimes times: Int) { count += amount * times } } var count = counter() count.incrementBy(2, numberOfTimes: 7) //处理变量可选值的时候 你可以在操作之前加? 之前的值是nil的话 那么后面的东西将不会被执行 否则 ? 后边的东西被运行 这种情况下 整个表达是只有一个可选值 let optionalSqare: Square = Square(sidelength: 2, name: "Alice", number: 3) let sidelength = optionalSqare.sidelength //枚举和结构体 enum Rank: Int { case Ace = 1 case Two, Three, Four, Five case Jack, Queen func simpleDescription() ->String { switch self { case .Ace: return "ace" case .Jack: return "jack" case .Queen: return "queen" default: return String(self.rawValue) } } } let ace = Rank.Ace let aceRowValue = ace.rawValue ace.simpleDescription() //写一个函数 来比较两个Rank的值 enum Ranks:Int { case one = 1 case two = 2 case three = 3 func sub(number1:Int, number2: Int) ->Int{ return number1 > number2 ? number1 : number2 } } let one = Ranks.one one.sub(10, number2: 2) //使用toRow 和fromRow函数在原始值和枚举值之间轻松切换 if let convertedRank = Rank(rawValue: 3) { let threeDescription = convertedRank.simpleDescription() threeDescription } //枚举的成员是实际值并不是原始值的另一种表达方法 实际上 如果原始之没有意义 你不需要设置 enum Suit { case Spades, Hearts, Diamonds, Clubs func simleDescription() ->String { switch self { case .Spades: return "spa" case .Hearts: return "hearts" case .Diamonds: return "dia" case .Clubs: return "clubs" } } } let hearts = Suit.Hearts let heartsDescription = hearts.simleDescription() //定义一个结构体 接受上边传来的东西 struct Card { var rank : Rank var suit : Suit func sipleDescription() -> String { return "(rank), (suit)" } } let thspeed = Card(rank: .Three, suit: .Spades) let thspeeds = thspeed.sipleDescription() thspeeds thspeed //通过枚举 却别正确错误信息 enum ServerResponse { case Result(String, String) case Error(String) } let success = ServerResponse.Result("Alice", "Dylan") let failure = ServerResponse.Error("Error") switch success { case let .Result(sunrise, sunset): let serverResponse = "(sunrise), (sunset)" case let .Error(error): let serverResponse = "Failure .. (error)" } //协议和扩展 //首先 使用protocal来声明一个协议 protocol ExampleRrotocol { var simpleDescription: String { get } mutating func adjust() } //类 枚举 结构体 都可以实现协议 class SimoleClass: ExampleRrotocol { var simpleDescription: String = "A very petit girl" var anotherpRroperty: Int = 69105 func adjust() { simpleDescription += "Alice" } } var a = SimoleClass() a.adjust() let aDescription = a.simpleDescription struct SimpleStructure : ExampleRrotocol { var simpleDescription: String = "Alice" mutating func adjust() { simpleDescription += ".Dylan" } } var b = SimpleStructure() b.adjust() let bDescription = b.simpleDescription </span>