码迷,mamicode.com
首页 > 编程语言 > 详细

Swift基础加强_跟我打500行

时间:2014-10-10 17:52:04      阅读:235      评论:0      收藏:0      [点我收藏+]

标签:des   style   blog   color   io   os   使用   ar   for   

今天上午、 继续练习了一下swift

然后 首先打开Xcode6

 

紧接着 我们创建一个playGround。  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 = 0
105 var maxtype = ""
106 for (kind, numbers) in interstingNumbers {
107     
108     for number in numbers {
109         if number > largest {
110             largest = number
111             maxtype = kind
112         }
113     }
114     
115 }
116 largest
117 maxtype
118 
119 // while
120 var n = 2
121 while n < 100 {
122     n = n*2
123 }
124 n
125 
126 var m  = 2
127 do {
128 m = m*2
129 } while m < 100
130 
131 m
132 
133 //  注意到了把  while do 不会多循环一次的  他们是等价的
134 
135 // ..<
136 var firstForLoop = 0
137 for i in 0..<4 {
138     firstForLoop += i
139 }
140 firstForLoop
141 
142 var secondForLoop = 0
143 for var i=0; i<4; i++ {
144     secondForLoop += i
145 }
146 secondForLoop
147 
148 var thirdForLoop = 0
149 for i in 0...4 {
150     thirdForLoop += i
151 }
152 thirdForLoop
153 
154 // func
155 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 = 0
171     
172     for score in scores {
173         
174         if score > max {
175             max = score
176         }
177         
178         if score < min {
179             min = score
180         }
181         
182         sum += score
183     }
184     
185     return (min, max, sum)
186 }
187 let staticArray = [1, 2, 3, 4, 5]
188 calculateStatistics(staticArray)
189 //  返回值可以用点语法单独的取到 也可以用位置
190 calculateStatistics(staticArray).sum
191 calculateStatistics(staticArray).0
192 
193 // 函数可以带有可变个数的参数
194 func sumOf(numbers: Int...) ->Int {
195     
196     var sum = 0
197     for number in numbers {
198         sum += number
199     }
200     return sum
201 }
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 = 0
210     for num in number {
211         sum += num
212     }
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 = 10
221     func add() {
222         y += 5
223     }
224     add()
225     return y
226 }
227 returnFifteen()
228 
229 // 函数可以作为另一个函数的返回值
230 func makeIncrementer() ->(Int->Int) {
231     
232     func addOne(number: Int) ->Int {
233         return 1 + number
234     }
235     return addOne
236 }
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 true
247         }
248     }
249     return false
250 }
251 
252 func lessThanTen(number: Int) ->Bool {
253     return number < 10
254 }
255 
256 var numbers = [20, 19, 2, 12]
257 hasAnymatches(numbers, lessThanTen)
258 
259 // 函数实际上是一特殊的闭包 使用{} 来创建一个匿名的闭包 使用int将参数和饭追只类型声明与闭包函数体进行分离
260 numbers.map({
261     (number: Int) -> Int in
262     let result = 3 * number
263     return result
264 })
265 
266 numbers.map({
267     (number: Int) -> Int in
268     if number % 2 != 0 {
269         return 0
270     }
271     return 1
272 })
273 
274 let mappedNumbers = numbers.map({
275     number in 3 * number
276 })
277 mappedNumbers
278 
279 let sortedNumbers = sorted(numbers) {
280     $0 > $1
281 }
282 sortedNumbers
283 
284 // 对象和类
285 class Shape {
286     var numberOdSides = 0
287     let testGetNumber = 0
288     
289     func setNumber(number: Int) {
290         numberOdSides = number
291     }
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 // init
304 class NamedShape {
305     var numberOfSides: Int = 0
306     var name:String
307     
308     init(name: String, number:Int) {
309         self.name = name
310         self.numberOfSides = number
311     }
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: Double
323     
324     init(sidelength: Double, name:String, number: Int) {
325         
326         self.sidelength = sidelength
327         super.init(name: name, number: number)
328     }
329     
330     func area() ->Double {
331         
332         return sidelength * sidelength
333     }
334     
335     override func simepleDescription() -> String {
336         return "a Square with Sides of Length \(sidelength)"
337     }
338 }
339 
340 // getter setter
341 class EquilaterTrabgle: NamedShape {
342     
343     var sideLengths: Double = 0.0
344     
345     init(side: Double, name: String, number: Int) {
346         self.sideLengths = side
347         super.init(name: name, number: number)
348     }
349     
350     var perimeter: Double {
351         
352         get {
353             return 3 * sideLengths
354         }
355         
356         set {
357             sideLengths = newValue / 3.0
358         }
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.perimeter
368 triangle.perimeter = 9.9
369 triangle.sideLengths
370 triangle.simepleDescription()
371 
372 // 默认的情况相爱 方法的参数名和他们在方法内部的名字一样
373 class counter {
374     var count: Int = 0
375     func incrementBy(amount: Int, numberOfTimes times: Int) {
376         count += amount * times
377     }
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.sidelength
385 
386 // 枚举和结构体
387 enum Rank: Int {
388     
389     case Ace = 1
390     case Two, Three, Four, Five
391     case Jack, Queen
392     
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.Ace
407 let aceRowValue = ace.toRaw()
408 ace.simpleDescription()
409 
410 // 写一个函数  来比较两个Rank值
411 enum Ranks: Int {
412     case one = 1
413     case two = 2
414     case three = 3
415     
416     func sub(number1: Int, number2: Int) ->Int {
417         
418         return number1 > number2 ? number1 : number2
419     }
420 }
421 let one = Ranks.one
422 one.sub(10, number2: 2)
423 
424 //  使用toRow 和fromRow函数在原始值和枚举值之前轻松的切换
425 if let convertedRank = Rank.fromRaw(3) {
426     let threeDescription = convertedRank.simpleDescription()
427     threeDescription
428 }
429 
430 // 枚举的成员是实际值并不是原始值的另一种表达方法 实际上 如果原始值没有意义 你不需要设置
431 enum Suit {
432     
433     case Spades, Hearts, Diamonds, Clubs
434     
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.Hearts
449 let heartsDescription = hearts.simleDescription()
450 
451 // 定义一个结构体 接受上边传来的东西
452 struct Card {
453     var rank: Rank
454     var suit: Suit
455     
456     func sipleDescription() ->String {
457         return "\(rank), \(suit)"
458     }
459 }
460 let thspeed = Card(rank: .Three, suit: .Spades)
461 let thspeeds = thspeed.sipleDescription()
462 thspeeds
463 thspeed
464 
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         get
487     }
488     mutating func adjust()
489 }
490 
491 // 类 枚举 结构体都可以实现协议
492 class SimoleClass: ExamplepRrotocol  {
493     var simpleDescription: String = "A very petit girl"
494     var anotherpRroperty: Int = 69105
495     func adjust() {
496         simpleDescription += "Alice"
497     }
498 }
499 
500 var a = SimoleClass()
501 a.adjust()
502 
503 let aDescription = a.simpleDescription
504 
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.simpleDescription
515 
516 // extension 为现有的类型添加功能
517 //extension Int: ExamplepRrotocol {
518 //    var simpleDescription: String {
519 //        return "the number \(self)"
520 //    }
521 //}

ok 大家又会有个提升。  加油喽

Swift基础加强_跟我打500行

标签:des   style   blog   color   io   os   使用   ar   for   

原文地址:http://www.cnblogs.com/Dylan-Alice/p/Swift_Strong.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!