首页 > 代码库 > Swift基础加强

Swift基础加强

创建一个playGround,然后看一下代码,跟着打,别复制粘贴。

  1 // Playground - noun: a place where people can play  2   3 import UIKit  4   5 // HelloWorld  6 var str = "Hello, playground"  7   8 // 常量可以改变值  9 var myVariable = 42 10 myVariable = 50 11 let myConstant = 42 12  13 // 指定数据类型 14 let floatNumber:Float = 4 15  16 // 使用强制转换 17 let lable = "the lable is " 18 let width = 94 19 let labelwidth = lable + String(width) 20  21 // 使用双引号中的\来转换 22 let apples = 3 23 let oranges = 5 24 let appleSummary = "i have \(apples) apples" 25 let orangeSummary = "i have \(oranges) oranges" 26  27 // 自动识别数据类型加斜杠转换 28 let somebody = "Alice" 29 let age = 23.5 30 let hellosomebody = "\(somebody) is \(age)" 31  32 // 数组的初始化以及赋值 33 var shoppingList = ["Alice", "Dylan"] 34 shoppingList[1] = "Petit Alice" 35  36 // 字典的初始化以及赋值 37 var occupations = [ 38  39     "male" : "Alice", 40     "female" : "Dylan" 41 ] 42 occupations["male"] = "Alice.Petit" 43  44 // 初始化一个空的数组或者字典 45 let emptyArray = [String]() 46 let emptyDictionary = [String:Float]() 47  48 // 初始化一个自动识别类型的字典或者数组 49 let emptyArray_auto = [] 50 let emptyDictionary_auto = [:] 51  52 // 控制流 不能省略大括号 53 let individualScores = [75, 42, 103, 87, 12] 54 var teamScore = 0 55 for score in individualScores { 56     if score > 50 { 57         teamScore += 3 58     } else { 59         teamScore += 1 60     } 61 } 62 teamScore 63  64 // 写到这里 突然发现 变量名称直接打出去 就能打印了 65 let emptyA = ["key": "value"] 66 emptyA 67  68 // 在if条件中 条件必须是bool表达式 输如一个直接score会出错的 看好了  是必须是表达式 69  70 // 使用let来标记 71 var optionalString: String? = "Hello" 72 optionalString == nil 73  74 var optionalName: String? = "John Appleseed" 75 var getting = "Hello" 76 optionalName = nil 77  78 if let name = optionalName { 79     getting = "hello, \(name)" 80 } else { 81     getting = "hello, Alice" 82 } 83  84 // switch 85 let vegetable = "red pepper" 86 switch vegetable { 87     case "celery": 88         let vegetableComment = "add some" 89     case "cummber", "watercress": 90         let vegetableComment = "this would make a good tea" 91 case let x where x.hasSuffix("pepper"): 92     let vegetableComment = "is it a spicy \(x)" 93 default: 94     let vegetableComment = "everything tastes good in soup" 95 } 96  97 // 碰到匹配的句子后 switch不会在继续往前走 98 let interstingNumbers = [ 99     "prime" : [2, 3, 4, 6],100     "Fibonacci" : [1, 1, 2, 3],101     "Square" : [1, 4, 5]102 ]103 104 var largest = 0105 var maxtype = ""106 for (kind, numbers) in interstingNumbers {107     108     for number in numbers {109         if number > largest {110             largest = number111             maxtype = kind112         }113     }114     115 }116 largest117 maxtype118 119 // while120 var n = 2121 while n < 100 {122     n = n*2123 }124 n125 126 var m  = 2127 do {128 m = m*2129 } while m < 100130 131 m132 133 //  注意到了把  while do 不会多循环一次的  他们是等价的134 135 // ..<136 var firstForLoop = 0137 for i in 0..<4 {138     firstForLoop += i139 }140 firstForLoop141 142 var secondForLoop = 0143 for var i=0; i<4; i++ {144     secondForLoop += i145 }146 secondForLoop147 148 var thirdForLoop = 0149 for i in 0...4 {150     thirdForLoop += i151 }152 thirdForLoop153 154 // func155 func greet(name:String, day:String) ->String {156     157     return "Hello. \(name), today is \(day)"158 }159 greet("Alice", "Tuesday")160 161 func whateating(name:String) ->String {162     return "\(name) eat what?"163 }164 whateating("Alice")165 166 // 使用元组让一个函数返回多个值167 func calculateStatistics(scores:[Int]) ->(min: Int, max:Int, sum:Int) {168     var min = scores[0]169     var max = scores[0]170     var sum = 0171     172     for score in scores {173         174         if score > max {175             max = score176         }177         178         if score < min {179             min = score180         }181         182         sum += score183     }184     185     return (min, max, sum)186 }187 let staticArray = [1, 2, 3, 4, 5]188 calculateStatistics(staticArray)189 //  返回值可以用点语法单独的取到 也可以用位置190 calculateStatistics(staticArray).sum191 calculateStatistics(staticArray).0192 193 // 函数可以带有可变个数的参数194 func sumOf(numbers: Int...) ->Int {195     196     var sum = 0197     for number in numbers {198         sum += number199     }200     return sum201 }202 sumOf(1, 2)203 sumOf()204 sumOf(1,2 ,3 ,4,5)205 206 // 计算参数平均值的联系207 func acr(number:Int...) ->Float {208     209     var sum = 0210     for num in number {211         sum += num212     }213     return Float(sum)/Float(number.count)214 }215 acr(1, 2, 3)216 acr(3, 4)217 218 // 函数可以嵌套 被嵌套的函数可以访问外侧函数的变量 可以嵌套函数来重构一个太长或者太复杂的函数219 func returnFifteen() ->Int {220     var y = 10221     func add() {222         y += 5223     }224     add()225     return y226 }227 returnFifteen()228 229 // 函数可以作为另一个函数的返回值230 func makeIncrementer() ->(Int->Int) {231     232     func addOne(number: Int) ->Int {233         return 1 + number234     }235     return addOne236 }237 238 var increment = makeIncrementer()239 increment(7)240 241 // 函数可以当做参数 传入另一个函数242 func hasAnymatches(list:[Int], condition:Int->Bool) ->Bool {243     244     for item in list {245         if condition(item) {246             return true247         }248     }249     return false250 }251 252 func lessThanTen(number: Int) ->Bool {253     return number < 10254 }255 256 var numbers = [20, 19, 2, 12]257 hasAnymatches(numbers, lessThanTen)258 259 // 函数实际上是一特殊的闭包 使用{} 来创建一个匿名的闭包 使用int将参数和饭追只类型声明与闭包函数体进行分离260 numbers.map({261     (number: Int) -> Int in262     let result = 3 * number263     return result264 })265 266 numbers.map({267     (number: Int) -> Int in268     if number % 2 != 0 {269         return 0270     }271     return 1272 })273 274 let mappedNumbers = numbers.map({275     number in 3 * number276 })277 mappedNumbers278 279 let sortedNumbers = sorted(numbers) {280     $0 > $1281 }282 sortedNumbers283 284 // 对象和类285 class Shape {286     var numberOdSides = 0287     let testGetNumber = 0288     289     func setNumber(number: Int) {290         numberOdSides = number291     }292     293     func simpleDescription() ->String {294         295         return "A shape with \(numberOdSides) sides"296     }297 }298 299 var shape = Shape()300 shape .setNumber(10)301 shape .simpleDescription()302 303 // init304 class NamedShape {305     var numberOfSides: Int = 0306     var name:String307     308     init(name: String, number:Int) {309         self.name = name310         self.numberOfSides = number311     }312     313     func simepleDescription() ->String {314         return "A \(name) with \(numberOfSides) sides"315     }316 }317 var nameShape = NamedShape(name: "Alice", number: 20)318 nameShape .simepleDescription()319 320 // 继承321 class Square: NamedShape {322     var sidelength: Double323     324     init(sidelength: Double, name:String, number: Int) {325         326         self.sidelength = sidelength327         super.init(name: name, number: number)328     }329     330     func area() ->Double {331         332         return sidelength * sidelength333     }334     335     override func simepleDescription() -> String {336         return "a Square with Sides of Length \(sidelength)"337     }338 }339 340 // getter setter341 class EquilaterTrabgle: NamedShape {342     343     var sideLengths: Double = 0.0344     345     init(side: Double, name: String, number: Int) {346         self.sideLengths = side347         super.init(name: name, number: number)348     }349     350     var perimeter: Double {351         352         get {353             return 3 * sideLengths354         }355         356         set {357             sideLengths = newValue / 3.0358         }359     }360     361     override func simepleDescription() -> String {362         return "an square triagle with \(sideLengths)"363     }364 }365 366 var triangle = EquilaterTrabgle(side: 3.1, name: "Alice", number: 3)367 triangle.perimeter368 triangle.perimeter = 9.9369 triangle.sideLengths370 triangle.simepleDescription()371 372 // 默认的情况相爱 方法的参数名和他们在方法内部的名字一样373 class counter {374     var count: Int = 0375     func incrementBy(amount: Int, numberOfTimes times: Int) {376         count += amount * times377     }378 }379 var count = counter();380 count.incrementBy(2, numberOfTimes: 7)381 382 // 处理变量的可选值的时候。 你可以在操作之前加?之前的值是nil的话那么后边的东西讲不会被执行 否则 ?后边的东西被运行 这种情况下 整个表达式只有一个可选值383 let optionalSquare: Square = Square(sidelength: 2, name: "Alice", number: 3)384 let sidelength = optionalSquare.sidelength385 386 // 枚举和结构体387 enum Rank: Int {388     389     case Ace = 1390     case Two, Three, Four, Five391     case Jack, Queen392     393     func simpleDescription() ->String {394         switch self {395         case .Ace:396             return "ace"397         case .Jack:398             return "jack"399         case .Queen:400             return "queen"401         default:402             return String(self.toRaw())403         }404     }405 }406 let ace = Rank.Ace407 let aceRowValue =http://www.mamicode.com/ ace.toRaw()408 ace.simpleDescription()409 410 // 写一个函数  来比较两个Rank值411 enum Ranks: Int {412     case one = 1413     case two = 2414     case three = 3415     416     func sub(number1: Int, number2: Int) ->Int {417         418         return number1 > number2 ? number1 : number2419     }420 }421 let one = Ranks.one422 one.sub(10, number2: 2)423 424 //  使用toRow 和fromRow函数在原始值和枚举值之前轻松的切换425 if let convertedRank = Rank.fromRaw(3) {426     let threeDescription = convertedRank.simpleDescription()427     threeDescription428 }429 430 // 枚举的成员是实际值并不是原始值的另一种表达方法 实际上 如果原始值没有意义 你不需要设置431 enum Suit {432     433     case Spades, Hearts, Diamonds, Clubs434     435     func simleDescription() -> String {436         switch self {437         case .Spades:438             return "spa"439         case .hearts:440             return "heart"441         case .Diamonds:442             return "dia"443         case .Clubs:444             return "clubs"445         }446     }447 }448 let hearts = Suit.Hearts449 let heartsDescription = hearts.simleDescription()450 451 // 定义一个结构体 接受上边传来的东西452 struct Card {453     var rank: Rank454     var suit: Suit455     456     func sipleDescription() ->String {457         return "\(rank), \(suit)"458     }459 }460 let thspeed = Card(rank: .Three, suit: .Spades)461 let thspeeds = thspeed.sipleDescription()462 thspeeds463 thspeed464 465 // 通过枚举 区别正确或者错误信息466 enum ServerResponse {467     case Result(String, String)468     case Error(String)469 }470 471 let success = ServerResponse.Result("Alice", "Dylan")472 let failure = ServerResponse.Error("Error")473 474 switch success {475 case let .Result(sunrise, sunset):476     let serverResponse = "\(sunrise), \(sunset)"477 case let .Error(error):478     let serverResponse = "Failure .. \(error)"479 }480 481 // 协议和扩展482 483 // 首先  使用protocal来申明一个协议 484 protocol ExamplepRrotocol {485     var simpleDescription: String {486         get487     }488     mutating func adjust()489 }490 491 // 类 枚举 结构体都可以实现协议492 class SimoleClass: ExamplepRrotocol  {493     var simpleDescription: String = "A very petit girl"494     var anotherpRroperty: Int = 69105495     func adjust() {496         simpleDescription += "Alice"497     }498 }499 500 var a = SimoleClass()501 a.adjust()502 503 let aDescription = a.simpleDescription504 505 struct SimpleStructure : ExamplepRrotocol{506     var simpleDescription: String = "Alice"507     mutating func adjust() {508         simpleDescription += ".Dylan"509     }510 }511 512 var b = SimpleStructure()513 b.adjust()514 let bDescription = b.simpleDescription515 516 // extension 为现有的类型添加功能517 //extension Int: ExamplepRrotocol {518 //    var simpleDescription: String {519 //        return "the number \(self)"520 //    }521 //}

Swift基础加强