Swift基础学习(三)《The Swift Programming Language 中文版》前言部分代码示例

  1 import UIKit
  2
  3 var str = "Hello, playground"
  4
  5 var myVariable = 42
  6 myVariable = 50
  7 let myConstant = 42
  8
  9 let implicitInteger = 70
 10 let implicitDouble = 70.0
 11 let explicitDouble: Double = 70
 12 let explicitFloat: Float = 4
 13
 14 let label = "The width is"
 15 let width = 94
 16 let widthLabel = label + String(width)
 17
 18 let apples = 3
 19 let oranges = 5
 20 let appleSummary = "I have \(apples) apples."
 21 let fruitSummary = "I have \(apples + oranges) pieces of fruit."
 22
 23 let float1 = 1.0
 24 let float2 = 3.0
 25 let floatString = "\(float1 + float2) CHM, Hi"
 26
 27 var shoppingList = ["catfish", "water", "tulips", "blue paint"]
 28 shoppingList[1] = "bottle of water"
 29
 30 var occupations = [
 31     "Malcolm": "Captain",
 32     "Kaylee": "Mechanic",
 33 ]
 34 occupations["Jayne"] = "public Relations"
 35
 36 let emptyArray = [String]()
 37 let emptyDictionary = [String: Float]()
 38 shoppingList = []
 39 occupations = [:]
 40
 41 let individualScores = [75, 43, 103, 87, 12]
 42 var teamScore = 0
 43 for score in individualScores {
 44     if score > 50 {
 45         teamScore += 3
 46     } else {
 47         teamScore += 1
 48     }
 49 }
 50 print(teamScore)
 51
 52 var optionalString: String? = "Hello"
 53 print(optionalString == nil)
 54
 55 var optionalName: String? = nil
 56 var greeting = "Hello!"
 57
 58 if let name = optionalName {
 59     greeting = "Hello, \(name)"
 60 } else {
 61     greeting = "Hello, CHM"
 62 }
 63
 64 let nickName: String? = nil
 65 let fullName: String = "John Appleseed"
 66 let informalGreeting = "Hi \(nickName ?? fullName)"
 67
 68 let vegetable = "red pepper"
 69 switch vegetable {
 70 case "celery":
 71     print("Add some raisins and make ants on a log")
 72     case "cucumber", "watercress":
 73     print("That would make a good tea sandwich.")
 74 case let x where x.hasSuffix("pepper"):
 75     print("Is it a spicy \(x)?")
 76 default:
 77     print("Everything tastes good in soup.")
 78 }
 79
 80 let interestingNumbers = [
 81     "Prime": [2, 3, 5, 7, 11, 13],
 82     "Fibonacci": [1, 1, 2, 3, 5, 8],
 83     "Square": [1, 4, 9, 16, 25],
 84 ]
 85
 86 var largest = 0
 87 var largestKind = ""
 88 for (kind, numbers) in interestingNumbers {
 89     for number in numbers {
 90         if number > largest {
 91             largest = number
 92             largestKind = kind
 93         }
 94     }
 95 }
 96
 97 print("\(largest, largestKind)")
 98
 99 var n = 2
100 while n < 100 {
101     n = n * 2
102 }
103 print(n)
104
105 var m = 2
106 repeat {
107     m = m * 2
108 } while m < 100
109 print(m)
110
111 var total = 0
112 for i in 0..<4 {
113     total += i
114 }
115 print(total)
116
117 func greet(person: String, day: String) -> String {
118     return "Hello \(person), today is \(day)."
119 }
120 greet(person: "Bob", day: "Thesday")
121
122 func eat(name: String, food: String) -> String {
123     return "\(name) eat \(food) today."
124 }
125
126 func greet(_ person: String, on day: String) -> String {
127     return "Hello \(person), today is \(day)."
128 }
129 greet("John", on: "Wednesday")
130
131 func calculateStatistics(scores: [Int]) -> (min: Int, max: Int, sum: Int) {
132     var min = scores[0]
133     var max = scores[0]
134     var sum = 0
135
136     for score in scores {
137         if score > max {
138             max = score
139         } else if score < min {
140             min = score
141         }
142         sum += score
143     }
144
145     return(min, max, sum)
146 }
147
148 let statistics = calculateStatistics(scores: [5, 3, 100, 3, 9])
149 print(statistics.sum)
150 print(statistics.2)
151
152 func sumOf(numbers: Int...) -> Int {
153     var sum = 0
154     for number in numbers {
155         sum += number
156     }
157     return sum
158 }
159
160 sumOf()
161 sumOf(numbers: 42, 597, 12)
162
163
164 func returnFifteen() -> Int {
165     var y = 0
166     func add() {
167         y += 5
168     }
169     add()
170     return y
171 }
172 returnFifteen()
173
174 func makeIncrementer() -> ((Int)-> Int) {
175     func addOne(number: Int) -> Int {
176         return 1 + number
177     }
178     return addOne
179 }
180
181 var increment = makeIncrementer()
182 increment(7)
183
184 func hasAnyMatches(list: [Int], condition: (Int) -> Bool) -> Int {
185     for item in list {
186         if condition(item) {
187             return item
188         }
189     }
190     return 0
191 }
192
193 func lessThanTen(number: Int) -> Bool {
194     return number < 10
195 }
196
197 var numbers = [20, 19, 7, 12]
198 hasAnyMatches(list: numbers, condition: lessThanTen)
199
200 numbers.map({
201     (number: Int) -> Int in
202     let result = 3 * number
203     return result
204 })
205
206 let mappedNumbers = numbers.map({number in 3 * number})
207 print(mappedNumbers)
208
209 //let sortedNumbers = numbers.sort{$0 > $1}
210 //print(sortedNumbers)
211
212 class Shape {
213     var numberOfSides = 0
214     let addLetCode = 0
215     func simpleDescription() -> String {
216         return "A shape with \(numberOfSides) sides."
217     }
218
219     func addLetCodeTest(par: Int) -> String {
220         return "a \(par) sides."
221     }
222 }
223
224 var shape = Shape()
225 shape.numberOfSides = 7
226 var shapeDescription = shape.simpleDescription()
227
228 class NamedShape {
229     var numberOfSides: Int = 0
230     var name: String
231
232     init(name: String) {
233         self.name = name
234     }
235
236     func simpleDescription() -> String {
237         return "A shape with \(numberOfSides) sides."
238     }
239 }
240
241 class Square: NamedShape {
242     var sideLength: Double
243
244     init(sideLength: Double, name: String) {
245         self.sideLength = sideLength
246         super.init(name: name)
247         numberOfSides = 4
248     }
249
250     func area() -> Double {
251         return sideLength * sideLength
252     }
253
254     override func simpleDescription() -> String {
255         return "A square with sides of length \(sideLength)."
256     }
257 }
258
259 let test = Square(sideLength: 5.2, name: "my test square")
260 test.area()
261 test.simpleDescription()
262
263 class EquilateralTriangle: NamedShape {
264     var sideLenth: Double = 0.0
265
266     init(sideLength: Double, name: String) {
267         self.sideLenth = sideLength
268         super.init(name: name)
269         numberOfSides = 3
270     }
271
272     var perimeter: Double {
273         get {
274             return 3.0 * sideLenth
275         }
276         set {
277             sideLenth = newValue / 3.0
278         }
279     }
280
281     override func simpleDescription() -> String {
282         return "An equilateral triagle with side of length \(sideLenth)."
283     }
284 }
285
286 var triangle = EquilateralTriangle(sideLength: 3.1, name: "a triangle")
287 print(triangle.perimeter)
288 triangle.perimeter = 9.9
289 print(triangle.sideLenth)
290
291 class TriangleAndSquare {
292     var triangle: EquilateralTriangle {
293         willSet {
294             square.sideLength = newValue.sideLenth
295         }
296     }
297
298     var square:Square {
299         willSet {
300             triangle.sideLenth = newValue.sideLength
301         }
302     }
303
304     init(size: Double, name: String) {
305         square = Square(sideLength: size, name: name)
306         triangle = EquilateralTriangle(sideLength: size, name: name)
307     }
308 }
309
310 var triangleAndSquare = TriangleAndSquare(size: 10, name: "another test shape")
311 print(triangleAndSquare.square.sideLength)
312 print(triangleAndSquare.triangle.sideLenth)
313 triangleAndSquare.square = Square(sideLength:50, name: "larger square")
314 print(triangleAndSquare.triangle.sideLenth)
315
316 enum Rank: Int {
317     case Ace
318     case Two, Three, Four, Five, Six, Seven, Eight, Nine, Ten
319     case Jack, Queen, King
320
321     func simpleDescription() -> String {
322         switch self {
323         case .Ace:
324             return "ace"
325         case .Jack:
326             return "jack"
327         case .Queen:
328             return "queen"
329         case .King:
330             return "king"
331         default:
332             return String(self.rawValue)
333         }
334     }
335
336 }
337
338 let ace = Rank.Ace
339 let aceRawValue = ace.rawValue
340
341 if let convertedRank = Rank(rawValue: 0) {
342     let threeDescription = convertedRank.simpleDescription()
343 }
344
345 enum Suit {
346     case Spades, Hearts, Diamonds, Clubs
347
348     func simpleDescription() -> String {
349         switch self {
350         case .Spades:
351             return "spades"
352         case .Hearts:
353             return "hearts"
354         case .Diamonds:
355             return "diamonds"
356         case .Clubs:
357             return "clubs"
358         }
359     }
360
361 }
362
363 let hearts = Suit.Hearts
364 let heartsDescription = hearts.simpleDescription()
365
366 enum ServerResponse {
367     case Result(String, String)
368     case Failure(String)
369 }
370
371 let success = ServerResponse.Result("6:00 am", "8:09 pm")
372 let failure = ServerResponse.Failure("Out of cheese.")
373
374 switch success {
375 case let .Result(sunrise, sunset):
376     let serverResponse = "Sunrise is at \(sunrise) and sunset is at \(sunset)."
377 case let .Failure(message):
378     print("Failure... \(message)")
379 }
380
381 struct Card {
382     var rank: Rank
383     var suit: Suit
384     func simpleDescription() -> String {
385         return "The \(rank.simpleDescription()) of \(suit.simpleDescription())"
386     }
387 }
388
389 let threeOfSpades = Card(rank: .Three, suit: .Spades)
390 let threeOfSpadesDescription = threeOfSpades.simpleDescription()
391
392 protocol ExampleProtocol {
393     var simpleDescription: String { get }
394     mutating func adjust ()
395 }
396
397 class SimpleClass: ExampleProtocol {
398     var simpleDescription: String = "A very simple class"
399     var anotherProperty: Int = 69105
400     func adjust() {
401         simpleDescription += "Now 100% adjusted."
402     }
403 }
404
405 var a = SimpleClass()
406 a.adjust()
407 let aDescription = a.simpleDescription
408
409 struct SimpleStructure: ExampleProtocol {
410     var simpleDescription: String = "A simple structure"
411     mutating func adjust() {
412         simpleDescription += "(adjusted)"
413     }
414 }
415
416 var b = SimpleStructure()
417 b.adjust()
418 let bDescription = b.simpleDescription
419
420 extension Int: ExampleProtocol {
421     var simpleDescription: String {
422         return "The number \(self)"
423     }
424     mutating func adjust() {
425         self += 42
426     }
427 }
428
429 print(7.simpleDescription)
430 let protocolValue: ExampleProtocol = a
431 print(protocolValue.simpleDescription)
432
433 enum PrinterError: Error {
434     case OutofPaper
435     case NoToner
436     case OnFire
437 }
438
439 func send(job: Int, toPrinter printerName:String) throws -> String {
440     if printerName == "Never Has Toner" {
441         throw PrinterError.OnFire
442     }
443     return "Job sent"
444 }
445
446 do {
447     let printerResponse = try send(job: 1040, toPrinter: "Never Has Toner")
448     print(printerResponse)
449 } catch {
450     print(error)
451 }
452
453 do {
454     let printerResponse = try send(job: 1440, toPrinter: "Never Has Toner")
455     print(printerResponse)
456 } catch PrinterError.OnFire {
457     print("I‘ll just put this over here, with rest of the fire.")
458 } catch let printerError as PrinterError {
459     print("Printer error: \(printerError).")
460 } catch {
461     print(error)
462 }
463
464
465 let printerSuccess = try? send(job: 1884, toPrinter: "Mergenthaler")
466 let printerFailure = try? send(job: 1885, toPrinter: "Never Has Toner")
467
468
469 var fridgeIsOpen = false
470 let fridgeContent = ["milk", "eggs", "leftovers"]
471
472 func fridgecontains (_ food: String) -> Bool {
473     fridgeIsOpen = true
474     defer {
475         fridgeIsOpen = false
476     }
477
478     let result = fridgeContent.contains(food)
479     return result
480 }
481
482 fridgecontains("milk")
483 print(fridgeIsOpen)
484
485 func repeatItem<Item>(repeating item: Item, numberOfTimers: Int) -> [Item] {
486     var result = [Item]()
487     for _ in 0..<numberOfTimers {
488         result.append(item)
489     }
490     return result
491 }
492 repeatItem(repeating: "knock", numberOfTimers: 2)
493
494 enum OptionalValue<Wrapped> {
495     case None
496     case Some(Wrapped)
497 }
498
499 var possibleInteger: OptionalValue<Int> = .None
500 possibleInteger = .Some(100)
501
502 func anyCommonElements<T: Sequence, U: Sequence>(_ lhs: T, _ rhs: U) -> Bool
503     where T.Iterator.Element: Equatable, T.Iterator.Element == U.Iterator.Element {
504         for lhsItem in lhs {
505             for rhsItem in rhs {
506                 if lhsItem == rhsItem {
507                     return true
508                 }
509             }
510         }
511         return false
512 }
513
514 anyCommonElements([1, 2, 3], [3])
时间: 2024-10-05 05:58:25

Swift基础学习(三)《The Swift Programming Language 中文版》前言部分代码示例的相关文章

The Swift Programming Language 中文版---Swift 初见

Swift 初见 本页内容包括: 简单值(Simple Values) 控制流(Control Flow) 函数和闭包(Functions and Closures) 对象和类(Objects and Classes) 枚举和结构体(Enumerations and Structures) 接口和扩展(Protocols and Extensions) 泛型(Generics) 通常来说,编程语言教程中的第一个程序应该在屏幕上打印"Hello, world".在 Swift 中,可以用

The Swift Programming Language 中文版

iSwifting社区 Swift 兴趣交流群:303868520 iOS 微信公众账号:iOSDevTip Swift 微信公众账号:SwiftDev iSwifting社区 如果你觉得这个项目不错,请点击Star一下,您的支持我们最大的动力. The Swift Programming Language 中文版 这一次,让中国和世界同步 The Swift Programming Language 中文版,布布扣,bubuko.com

一群牛人翻译:The Swift Programming Language 中文版

无聊闲逛GIthub,看到一群牛人在github上创建了一个关于Switf的文档翻译项目 The Swift Programming Language 中文版 项目地址:中文版 Apple 官方 Swift 教程<The Swift Programming Language> 需要的小伙伴们速度去查阅. 到现在6月12日下午4:59.英文版的手册仅发布9天. star和fork的数量增长惊人 一群牛人翻译:The Swift Programming Language 中文版

Python入门基础学习 三

Python入门基础学习 三 数据类型 Python区分整型和浮点型依靠的是小数点,有小数点就是浮点型. e记法:e就是10的意思,是一种科学的计数法,15000=1.5e4 布尔类型是一种特殊的整形,true就相当于1,false相当于0,可以用来计算 类型转换 转换:整数:int();字符串:str();浮点数:float() 转换例子:(图9) 如果用内置函数当变量名,比如str=123,一旦被赋值,再使用这个函数会被报错. type()函数可以明确告诉我们变量类型. isinstance

分享《TensorFlow实战Google深度学习框架 (第2版) 》中文版PDF和源代码

下载:https://pan.baidu.com/s/1aD1Y2erdtppgAbk8c63xEw 更多最新的资料:http://blog.51cto.com/3215120 <TensorFlow实战Google深度学习框架(第2版)>中文版PDF和源代码中文版PDF,带目录标签,文字可以复制,363页.配套源代码:经典书籍,讲解详细:如图 原文地址:https://www.cnblogs.com/javapythonstudy/p/9873505.html

《TensorFlow实战Google深度学习框架 (第2版) 》中文版PDF和源代码

下载:https://pan.baidu.com/s/1aD1Y2erdtppgAbk8c63xEw 更多最新的资料:http://blog.51cto.com/3215120 <TensorFlow实战Google深度学习框架(第2版)>中文版PDF和源代码中文版PDF,带目录标签,文字可以复制,363页.配套源代码:经典书籍,讲解详细:如图 原文地址:http://blog.51cto.com/3215120/2310423

Swift基础学习(一)基本语法

Swift 简介(赞美一番,收集了多篇 关于Swift 学习教程的语言简介一直以为英语和汉语混写的时候只是英语字母结尾的地方打空格,原来是英语字母的开头和结尾都要加一个空格,英语字母后面是标点符号的时候不加空格): Swift 是一种新的编程语言,用于编写 iOS,macOS,watchOS 和 tvOS 的应用程序.Swift 结合了 C 和 Objective-C 的优点并且不受 C 兼容性的限制.Swift 采用安全的编程模式并添加了很多新特性,这将使编程更简单,更灵活,也更有趣.Swif

Dango基础学习三

今天主要来学习一下Django的路由系统,视频中只学了一些皮毛,但是也做下总结,主要分为<静态路由>.<动态路由>.<二级路由> 一.先来看下静态路由 1.需要在project中的urls文件中做配置,然后将匹配到的urls转发到对应app的views的函数中 2.在对应的app的views中配置相应的函数 3.这个时候我们通过浏览器访问这个url,就可以得到如下的结果 ok.至此,静态路由我们就学习完了,下面我们开始学习动态路由 二.动态路由的学习,动态路由的学习主要

swift基础学习(04)[运算符、属性、属性观察器、方法、下脚标本、继承、构造器]

//swift恒等运算符 //===恒等,不等!== //运用这两个运算符检测两个常量或者变量是否引用同一个实例 //"等价于"表示两个类类型(class type)的常量或者变量引用同一个类实例. //等于"表示两个实例的值"相等"或"相同",判定时要遵照设计者定义的评判标准,因此相对于"相 等"来说,这是一种更加合适的叫法. //类和结构体的选择 //属性的存储只能是类或者是结构体 //存储属性:变量存储属性va