Swift3.0基础语法学习<一>

  1 //
  2 //  ViewController.swift
  3 //  SwiftBasicDemo
  4 //
  5 //  Created by 思 彭 on 16/11/15.
  6 //  Copyright © 2016年 思 彭. All rights reserved.
  7 //
  8 
  9 import UIKit
 10 
 11 class ViewController: UIViewController {
 12 
 13     override func viewDidLoad() {
 14         super.viewDidLoad()
 15         
 16         // 1.常量,变量, 类型转换
 17         let label = "The Width is"
 18         let width = 94
 19         let widthLabel = label + String(width)
 20         
 21         //2.拼接字符串
 22         let apples = 3
 23         let oranges = 5
 24         let appleSummany = "I have (apples) apples"
 25         let fruitSummany = "I have (apples + oranges) fruits"
 26         
 27         // 3.数组,字典的使用
 28         var shoppingList = ["catfish", "water", "tulips", "blue paint"]
 29         shoppingList[1] = "bottle of water"
 30         var occupations = [
 31             "Malcolm": "Captain",
 32             "Kaylee": "Mechanic",
 33         ]
 34         // 当没有key,则默认师插入,否则是修改
 35         occupations["janyne"] = "Public Relations"
 36         
 37         // 4.创建空字典,空数组
 38         let emptyArray = [String]()
 39         let emptyDic = [String: Float]()
 40         
 41         // 当类型可以被推断,使用以下方法是错误的
 42         /*
 43         let emptyArray1 = []
 44         let emptyDic1 = [:]
 45         */
 46         
 47         shoppingList = []
 48         occupations = [:]
 49         
 50         // 5.if条件判断
 51         let individualScores = [75, 78,43, 89, 12]
 52         var teamScore = 0
 53         for score in individualScores {
 54             if score > 50 {
 55                 teamScore += 3
 56             }
 57             else {
 58                 teamScore += 1
 59             }
 60         }
 61         print("teamScore = (teamScore)")
 62         
 63         // 6.可选类型?
 64         var optionString: String? = "Hello"
 65         print(optionString == nil)  // false
 66         
 67         var optionName: String? = "John Appleseed"
 68         var greeting = "Hello!"
 69         // 守护
 70         if let name = optionName {
 71             greeting = "Hello,(name)"
 72         }
 73         print("greeting = (greeting)")
 74         
 75         // 7.可选值为nil  ??类似三目 当可选类型不存在为nil,则使用??后面的默认值
 76         let nickName: String? = nil
 77         let fullName: String = "John Appleseed"
 78         let informalGreeting = "Hi (nickName ?? fullName)"
 79         print(informalGreeting)
 80         
 81         // 8.Switch的使用
 82         let vegetable = "red pepper"
 83         switch vegetable {
 84         case "celery":
 85             print("Add some raisins and make ants on a log.")
 86         case "cucumber", "watercress":  //多个值
 87             print("That would make a good tea sandwich.")
 88         case let x where x.hasSuffix("pepper"): //  条件判断
 89             print("Is it a spicy (x)?")
 90             // 注意:default必须有,否则报错
 91         default:
 92             print("Everything tastes good in soup.")
 93         }
 94         
 95         // 9. 元组的使用  找出最大值 
 96         // 注意: 最后一个,可要可不要,都不会报错
 97         let interestingNumbers = [
 98             "Prime" : [2, 3, 5, 7, 11, 13],
 99             "Fibonacci": [1, 1, 2, 3, 5, 8],
100             "Square": [1, 4, 9, 16, 25]
101         ]
102         var largest = 0
103         for (kind, numbers) in interestingNumbers {
104             print(kind)
105             for number in numbers {
106                 if number > largest {
107                     largest = number
108                 }
109             }
110         }
111         print(largest)
112         
113         // 10. while循环   2 可能一次也不执行
114         var n = 2
115         while n < 2 {
116             n = n * 2
117         }
118         print(n)
119         
120         //  repeat while循环   4 注意:至少会执行一次
121         var m = 2
122         repeat {
123             m = m * 2
124         }while m < 2
125         print(m)
126         
127         // 11. ..<的使用  6
128         var total = 0
129         for i in 0..<4 {  // 注意不要使用空格,否则报错
130             total += i
131         }
132         print("total = (total)")
133         
134         // 12: 函数和元组
135         // 返回值为string
136         func greet(person: String, day: String) -> String {
137             
138             return "Hello (person),today = (day)."
139         }
140         //函数调用
141         let str = greet(person: "SiSi", day: "Tuesday")
142         print("str = (str)")
143         
144         // 13. _参数名可以省略
145         func greet1 (_ person: String, on day:  String) -> String {
146             
147             return "Hello (person), today is (day)"
148         }
149         print(greet1("haha", on: "hahahah"))
150         
151         // 14. 元组 --- 函数返回多个值
152         func calculatevalue(scores: [Int]) -> (min: Int, max: Int, sum: Int) {
153             
154             var min = scores[0]
155             var max = scores[0]
156             var sum = 0
157             for score in scores {
158                 if score > max {
159                     max = score
160                 }
161                 else if score < min {
162                     min = score
163                 }
164                 sum += score
165             }
166             return (min, max, sum)
167         }
168         
169         // 函数调用
170         let result = calculatevalue(scores: [34, 56, 23, 13, 78])
171         print(result.min)
172         print(result.max)
173         print(result.2)  // 下标调用: 注意: 下标从0开始
174         
175         // 15.参数不特定指定数组 每一个值为Int
176         func sumOf(numbers: Int...) ->Int {
177             
178             var sum = 0
179             for number in numbers {
180                 sum += number
181             }
182             return sum
183         }
184         print(sumOf(numbers: 32,45,67,88))
185         
186         // 16.函数的嵌套  15
187         func returnFifteen() ->Int {
188             
189             var y = 10
190             func add() {
191                 y += 5
192             }
193             add()
194             return y
195         }
196         print(returnFifteen())
197         
198         // 17. 函数的返回值是一个函数类型  8
199         func makeIncrement() -> ((Int) -> Int) {
200             func addOne(number: Int) -> Int {
201                 return 1 + number
202             }
203             return addOne
204         }
205         var increment = makeIncrement()
206         print(increment(7))
207         
208         // 18. 函数的参数是函数类型   true
209         func hasAnyMatches(list: [Int], condition: (Int) -> Bool) -> Bool {
210            
211             for item in list {
212                 if condition(item) {
213                     return true
214                 }
215             }
216             return false
217         }
218         func lessThanTen(number: Int) -> Bool {
219             
220             return number < 10
221         }
222         var numbers = [20, 19, 7, 12]
223         print(hasAnyMatches(list: numbers, condition: lessThanTen))
224         
225         // 19. map
226         numbers.map({
227             
228             (number: Int) -> Int in
229             let result = 3 * number
230             return result
231             })
232         let mappedNumbers = numbers.map { (number) in
233              3 * number
234         }
235         print(mappedNumbers)
236     }
237 }

每一条对应每一个语法知识点,注释很详细哟!!!

原文地址:https://www.cnblogs.com/pengsi/p/6066490.html