突然兴起复习一下Swift3.0
/// 参考Swift3.0.1文档 /// 摘录来自: Apple Inc. “The Swift Programming Language (Swift 3.0.1)”。 iBooks. import UIKit class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() aSwiftTour() } func aSwiftTour(){ //Swift中的输出语句 print("Hello World") //MARK: - 变量 /**var声明变量 Swift具备自动推导的能力 右边是什么类型这个变量或者是常量就自动的是什么类型了 */ var variable = 66 variable = 88 //MARK: - let声明常量 let constant = 66 print(variable,constant) //指定变量的类型 隐式指定 let implictInteger = 66 //Int let implicitDouble = 66.0 //Double //显式地指定类型为Double let explicitDouble: Double = 88 //Double print(implictInteger,implicitDouble,explicitDouble) let label = "The width is" let width = 94 let widthLabel = label + String(width) print(widthLabel) //MARK: - 数字和字符串的拼接 let apples = 3 let oranges = 5 let appleSummary = "I have \(apples) apples." let fruitSummary = "I have \(apples + oranges) pieces of fruit." //MARK: - 数组操作 var shoppingList = ["catfish", "water", "tulips", "blue paint"] shoppingList[1] = "bottle of water" //MARK: - 字典操作 key:value var occupations = [ "Malcolm": "Captain", "Kaylee": "Mechanic", ] occupations["Jayne"] = "Public Relations" //创建空数组和空字典的方式 //创建一个元素类型为字符串的数组 let emptyArray = [String]() //key为String类型value为Float类型的字典 let emptyDictionary = [String: Float]() //MARK: - 数组字典更简单的方式 /** “If type information can be inferred, you can write an empty array as [] and an empty dictionary as [:]—for example, when you set a new value for a variable or pass an argument to a function.” 摘录来自: Apple Inc. “The Swift Programming Language (Swift 3.0.1)”。 iBooks. */ shoppingList = []//默认是[String] occupations = [:]//默认是[String:String] //MARK: - 控制流 //注意for if else 的格式 let individualScores = [75, 43, 103, 87, 12] var teamScore = 0 for score in individualScores { if score > 50 { teamScore += 3 } else { teamScore += 1 } } print(teamScore) //MARK: - ?是可选值类型 var optionalString: String? = "Hello" print(optionalString == nil) var optionalName: String? = "John Appleseed" var greeting = "Hello!" if let name = optionalName { greeting = "Hello, \(name)" } //MARK: - “Another way to handle optional values is to provide a default value ”“using the ?? operator. If the optional value is missing, the default value is used instead.” let nickName: String? = nil let fullName: String = "John Appleseed" let informalGreeting = "Hi \(nickName ?? fullName)" /** (lldb) po nickName nil (lldb) po fullName "John Appleseed" (lldb) po informalGreeting "Hi John Appleseed" */ //MARK: - Switch Case的用法 let vegetable = "red pepper" switch vegetable { case "celery": print("Add some raisins and make ants on a log.") case "cucumber", "watercress": print("That would make a good tea sandwich.") //用x来标识vegetable 看看这个字符串的尾部是否有pepper Returns a Boolean value indicating whether the string ends with the specified suffix. case let x where x.hasSuffix("pepper"): print("Is it a spicy \(x)?") //Is it a spicy red pepper? default: print("Everything tastes good in soup.") } //MARK: - 快速遍历数组 并且找出来最大值 /** 三个字典还是鄙视比较好玩的 素数 斐波那契数列 平方 */ let interestingNumbers = [ "Prime": [2, 3, 5, 7, 11, 13], "Fibonacci": [1, 1, 2, 3, 5, 8], "Square": [1, 4, 9, 16, 25], ] var largest = 0 for (kind, numbers) in interestingNumbers { for number in numbers { if number > largest { largest = number } } } print(largest) //25 //MARK: - 循环 var n = 2 while n < 100 { n = n * 2 } print(n) //128 var m = 2 //就类似于do while repeat { m = m * 2 } while m < 100 print(m) //128 /** “Use ..< to make a range that omits its upper value, and use ... to make a range that includes both values.” */ var total = 0 for i in 0..<4 { total += i //1 2 3 } print(total)//6 var totalBoth = 0 for i in 0...4 { totalBoth += i//1 2 3 4 } print(totalBoth)//10 //MARK: - 函数和闭包 //函数 函数参数 返回值 func greet(person: String, day: String) -> String { return "Hello \(person), today is \(day)." } let s = greet(person: "Bob", day: "Tuesday") //"Hello Bob, today is Tuesday." 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 } else if score < min { min = score } sum += score } return (min, max, sum) } let statistics = calculateStatistics(scores: [5, 3, 100, 3, 9]) print(statistics.sum) print(statistics.2) //120 120 /** (lldb) po statistics.min 3 (lldb) po statistics.max 100 (lldb) po statistics.sum 120 */ //可变参数的函数 zhu'yi func sumOf(numbers: Int...) -> Int { var sum = 0 for number in numbers { sum += number } return sum } let sumOfEmptyParam = sumOf() let sumOfThree = sumOf(numbers: 42, 597, 12) /** (lldb) po sumOfEmptyParam 0 (lldb) po sumOfThree 651 */ //函数A的内部有函数B 函数A内部还调用了函数B func returnFifteen() -> Int { var y = 10 func add() { y += 5 } add() return y } let fifteenFunc = returnFifteen() //15 //参数为空 返回值为闭包类型 func makeIncrementer() -> ((Int) -> Int) { //参数为整型 返回值为整数 func addOne(number: Int) -> Int { return 1 + number } return addOne } var increment = makeIncrementer() increment(7) //8 //“A function can take another function as one of its arguments. //函数的返回值是一个函数 而且不仅仅是一个函数那么简单 只可意会哈哈 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, 7, 12] let nubersB = hasAnyMatches(list: numbers, condition: lessThanTen) //true 7满足条件 print(nubersB) //MARK: - 闭包 //“You can write a closure without a name by surrounding code with braces ({}). ” //到了闭包了 先停一下😄 numbers.map({ (number: Int) -> Int in let result = 3 * number return result }) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } }
我会不定期分享 iOS 相关技术文章