[关闭]
@luckyJerry 2016-03-01T13:12:33.000000Z 字数 4911 阅读 416

Swift入门笔记

iOS Swift


https://developer.apple.com/swift/resources/

简单类型

  1. let label = "The width is "
  2. let width = 94
  3. let widthLabel = label + String(width)
  1. let apples = 3
  2. let oranges = 5
  3. let appleSummary = "I have \(apples) apples."
  4. let fruitSummary = "I have \(apples + oranges) pieces of fruit."
  1. var shoppingList = ["catfish", "water", "tulips", "blue paint"]
  2. shoppingList[1] = "bottle of water"
  3. var occupations = [
  4. "Malcolm": "Captain",
  5. "Kaylee": "Mechanic",
  6. ]
  7. occupations["Jayne"] = "Public Relations"

创建空array和Dictionary

  1. let emptyArray = [String]()
  2. let emptyDictionary = [String: Float]()

如果类型可以推测的话,可以写得更简单

  1. shoppingList = []
  2. occupations = [:]

流程控制

if and switch to make conditionals,
use for-in, for, while, and repeat-while to make loops
条件上()可选. Body上 {}必须

  1. let vegetable = "red pepper"
  2. switch vegetable {
  3. case "celery":
  4. print("Add some raisins and make ants on a log.")
  5. case "cucumber", "watercress":
  6. print("That would make a good tea sandwich.")
  7. case let x where x.hasSuffix("pepper"):
  8. print("Is it a spicy \(x)?")
  9. default:
  10. print("Everything tastes good in soup.")
  11. }
  1. let interestingNumbers = [
  2. "Prime": [2, 3, 5, 7, 11, 13],
  3. "Fibonacci": [1, 1, 2, 3, 5, 8],
  4. "Square": [1, 4, 9, 16, 25],
  5. ]
  6. var largest = 0
  7. for (kind, numbers) in interestingNumbers {
  8. for number in numbers {
  9. if number > largest {
  10. largest = number
  11. }
  12. }
  13. }
  14. print(largest)

..< 标识循环范围,下面2个循环是一回事

  1. var firstForLoop = 0
  2. for i in 0..<4 {
  3. firstForLoop += i
  4. }
  5. print(firstForLoop)
  6. var secondForLoop = 0
  7. for var i = 0; i < 4; ++i {
  8. secondForLoop += i
  9. }
  10. print(secondForLoop)

ps ..<4 不包括4 , ...4 包括4

  1. var n = 2
  2. while n < 100 {
  3. n = n * 2
  4. }
  5. print(n)
  6. var m = 2
  7. repeat {
  8. m = m * 2
  9. } while m < 100
  10. print(m)
  1. let nickName: String? = nil
  2. let fullName: String = "John Appleseed"
  3. let informalGreeting = "Hi \(nickName ?? fullName)"

Functions and Closures

  1. func greet(name: String, day: String) -> String {
  2. return "Hello \(name), today is \(day)."
  3. }
  1. func calculateStatistics(scores: [Int]) -> (min: Int, max: Int, sum: Int) {
  2. var min = scores[0]
  3. var max = scores[0]
  4. var sum = 0
  5. for score in scores {
  6. if score > max {
  7. max = score
  8. } else if score < min {
  9. min = score
  10. }
  11. sum += score
  12. }
  13. return (min, max, sum)
  14. }
  15. let statistics = calculateStatistics([5, 3, 100, 3, 9])
  16. print(statistics.sum)
  17. print(statistics.2)
  1. func sumOf(numbers: Int...) -> Int {
  2. var sum = 0
  3. for number in numbers {
  4. sum += number
  5. }
  6. return sum
  7. }
  8. sumOf()
  9. sumOf(42, 597, 12)
  1. func returnFifteen() -> Int {
  2. var y = 10
  3. func add() {
  4. y += 5
  5. }
  6. add()
  7. return y
  8. }
  9. returnFifteen()
  1. func makeIncrementer() -> ((Int) -> Int) {
  2. func addOne(number: Int) -> Int {
  3. return 1 + number
  4. }
  5. return addOne
  6. }
  7. var increment = makeIncrementer()
  8. increment(7)

也可以把方法作为参数传递

  1. func hasAnyMatches(list: [Int], condition: (Int) -> Bool) -> Bool {
  2. for item in list {
  3. if condition(item) {
  4. return true
  5. }
  6. }
  7. return false
  8. }
  9. func lessThanTen(number: Int) -> Bool {
  10. return number < 10
  11. }
  12. var numbers = [20, 19, 7, 12]
  13. hasAnyMatches(numbers, condition: lessThanTen)
  1. numbers.map({
  2. (number: Int) -> Int in
  3. let result = 3 * number
  4. return result
  5. })

如果一个closure的类型已知,例如是一个delegate的callback,那么可以省略参数和返回类型

  1. let mappedNumbers = numbers.map({ number in 3 * number })
  2. print(mappedNumbers)

可以使用变量的编号而不是变量的名字来引用参数 $0
如果一个closure是某个方法唯一的参数的话,可以省略外面的()

  1. let sortedNumbers = numbers.sort { $0 < $1 }
  2. print(sortedNumbers)

对象和类

  1. class Shape {
  2. var numberOfSides = 0
  3. func simpleDescription() -> String {
  4. return "A shape with \(numberOfSides) sides."
  5. }
  6. }
  1. var shape = Shape()
  2. shape.numberOfSides = 7
  3. var shapeDescription = shape.simpleDescription()
  1. class NamedShape {
  2. var numberOfSides: Int = 0
  3. var name: String
  4. init(name: String) {
  5. self.name = name
  6. }
  7. func simpleDescription() -> String {
  8. return "A shape with \(numberOfSides) sides."
  9. }
  10. }

* deinit相当于NSObject 中的 dealloc方法。

  1. class Square: NamedShape {
  2. var sideLength: Double
  3. init(sideLength: Double, name: String) {
  4. self.sideLength = sideLength
  5. super.init(name: name)
  6. numberOfSides = 4
  7. }
  8. func area() -> Double {
  9. return sideLength * sideLength
  10. }
  11. override func simpleDescription() -> String {
  12. return "A square with sides of length \(sideLength)."
  13. }
  14. }
  15. let test = Square(sideLength: 5.2, name: "my test square")
  16. test.area()
  17. test.simpleDescription()
  1. class EquilateralTriangle: NamedShape {
  2. var sideLength: Double = 0.0
  3. init(sideLength: Double, name: String) {
  4. self.sideLength = sideLength
  5. super.init(name: name)
  6. numberOfSides = 3
  7. }
  8. var perimeter: Double {
  9. get {
  10. return 3.0 * sideLength
  11. }
  12. set {
  13. sideLength = newValue / 3.0
  14. }
  15. }
  16. override func simpleDescription() -> String {
  17. return "An equilateral triangle with sides of length \(sideLength)."
  18. }
  19. }
  20. var triangle = EquilateralTriangle(sideLength: 3.1, name: "a triangle")
  21. print(triangle.perimeter)
  22. triangle.perimeter = 9.9
  23. print(triangle.sideLength)

willSet 和 didSet 会在设置一个property的newValue的时候运行

  1. class TriangleAndSquare {
  2. var triangle: EquilateralTriangle {
  3. willSet {
  4. square.sideLength = newValue.sideLength
  5. }
  6. }
  7. var square: Square {
  8. willSet {
  9. triangle.sideLength = newValue.sideLength
  10. }
  11. }
  12. init(size: Double, name: String) {
  13. square = Square(sideLength: size, name: name)
  14. triangle = EquilateralTriangle(sideLength: size, name: name)
  15. }
  16. }

? 表示可能为空

  1. let optionalSquare: Square? = Square(sideLength: 2.5, name: "optional square")
  2. let sideLength = optionalSquare?.sideLength

枚举和结构体

Protocols and Extensions

添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注