Swift 整理(一)——初探小海鸥

  • let 来声明常量,使用 var 来声明变量。
    常量let 只能赋值1次,变量var 可以多次。

  • 不同类型的常量变量运算,需要强转:
    例:

let label = "The width is"
let width = 94
let widthLabel = label + String(width)

强转字符串可以简化:加反斜杠括号 \

let apples = 3
let oranges = 5
let appleSummary = "I have \(apples) apples."
let fruitSummary = "I have \(apples + oranges) pieces of fruit."
  • 使用 [] 来创建数组和字典
var shoppingList = ["catfish", "water", "tulips", "blue paint"]
shoppingList[1] = "bottle of water"
//字符数组
var occupations = [
    "Malcolm": "Captain",
    "Kaylee": "Mechanic",
]
occupations["Jayne"] = "Public Relations"
//字典:键值对

 let emptyArray = [String]()   //空字符数组
 let emptyDictionary = [String: Float]()  //空字典
  • 使用 if 和 switch 来进行条件操作,使用 for-in 、 for 、 while 和 repeat-while 来进行循环。

..< 来表示范围——半闭半开
... 来表示范围——闭区间

//for-in循环
let individualScores = [75, 43, 103, 87, 12]
var teamScore = 0
for score in individualScores {
    if score > 50 {
        teamScore += 3
    } else {
        teamScore += 1
} }
print(teamScore)

var total = 0
for i in 0..<4 {
total += i }
print(total)


//while循环
var n = 2
while n < 100 {
  n=n* 2 
}
print(n)

var m = 2
repeat {
m=m* 2
} while m < 100
print(m)


//switch条件
 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.")
 case let x where x.hasSuffix("pepper"):
     print("Is it a spicy \(x)?")
 default:
     print("Everything tastes good in soup.")
 }
//注:不用加break
  • 函数和闭包:func声明函数 ->指定返回值类型
func greet(_person: String, day: String) -> String {
    return "Hello \(person), today is \(day)."
}
greet(person:"Bob", day: "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)

//参数可以有多个
func sumOf(numbers: Int...) -> Int {
     var sum = 0
     for number in numbers {
         sum += number
}
return sum }
 sumOf()
 sumOf(numbers: 42, 597, 12)

闭包:用 {} 来创建 一个匿名闭包。使用 in 将参数和返回值类型声明与闭包函数体进行分离。

//闭包
 numbers.map({
     (number: Int) -> Int in
     let result = 3 * number
     return result
})

//单个语句闭包会把它语句的值当做结果返回
 let mappedNumbers = numbers.map({ number in 3 * number })
 print(mappedNumbers)

//当一个闭包是传给函数的唯一参数,你可以完全忽略括号。
 let sortedNumbers = numbers.sort { $0 > $1 }
 print(sortedNumbers)
  • 类与对象
//类
class NamedShape {
    var numberOfSides: Int = 0
    var name: String
    init(name: String) {
         self.name = name
    }
    func simpleDescription() -> String {
         return "A shape with \(numberOfSides) sides."
    }
}

//子类
class Square: NamedShape {
     var sideLength: Double
     init(sideLength: Double, name: String) {
         self.sideLength = sideLength
         super.init(name: name)
         numberOfSides = 4
      }
     func area() ->  Double {
         return sideLength * sideLength
      }
     override func simpleDescription() -> String {
         return "A square with sides of length \(sideLength)."
      } 
}
 let test = Square(sideLength: 5.2, name: "my test square")
 test.area()
 test.simpleDescription()

方法、属性和子脚本)之前加 ? 。如果 ? 之前的值是 nil , ? 后面 的东西都会被忽略,并且整个表达式返回 nil 。否则, ? 之后的东西都会被运行

 let optionalSquare: Square? = Square(sideLength: 2.5, name:"optional square")
 let sideLength = optionalSquare?.sideLength
  • 枚举和结构体:
//枚举:
enum Rank: Int {
    case Ace = 1
    case Two, Three, Four, Five, Six, Seven, Eight, Nine, Ten
    case Jack, Queen, King
    func simpleDescription() -> String {
        switch self {
        case .Ace:
            return "ace"
        case .Jack:
            return "jack"
        case .Queen:
            return "queen"
        case .King:
            return "king"
        default:
            return String(self.rawValue)
        }
    } 
}
let ace = Rank.Ace
let aceRawValue = ace.rawValue
  • 协议protocol
protocol ExampleProtocol {
    var simpleDescription: String { get }
    mutating func adjust()
}

//类、枚举和结构体都可以实现协议。
class SimpleClass: ExampleProtocol {
    var simpleDescription: String = "A very simple class."
    var anotherProperty: Int = 69105
    func adjust() {
        simpleDescription += "  Now 100% adjusted."
    }
}
var a = SimpleClass()
a.adjust()
let aDescription = a.simpleDescription
struct SimpleStructure: ExampleProtocol {
    var simpleDescription: String = "A simple structure"
    mutating func adjust() {
        simpleDescription += " (adjusted)"
    }
}
var b = SimpleStructure()
b.adjust()
let bDescription = b.simpleDescription
  • 错误处理:采用Error协议的类型来表示错误
enum PrinterError: Error {
    case OutOfPaper
    case NoToner
    case OnFire 
}

使用 throw 来抛出一个错误并使用 throws 来表示一个可以抛出错误的函数。如果在函数中抛出一个错误,这个函 数会立刻返回并且调用该函数的代码会进行错误处理。

func send(job: Int, toPrinter printerName: String) throws -> String {
    if printerName == "Never Has Toner" {
        throw PrinterError.noToner
    }
    return "Job sent"
}

有多种方式可以用来进行错误处理。一种方式是使用 do-catch 。在 do 代码块中,使用 try 来标记可以抛出错误 的代码。在 catch 代码块中,除非你另外命名,否则错误会自动命名为 error 。

do {
    let printerResponse = try send(job: 1040, toPrinter: "Bi Sheng")
    print(printerResponse)
} catch {
    print(error)
}

//catch可以使用多个 来解决不同的特定的错误
do {
    let printerResponse = try send(job: 1440, toPrinter: "Gutenberg")
    print(printerResponse)
 } catch PrinterError.onFire {
     print("I'll just put this over here, with the rest of the fire.")
 } catch let printerError as PrinterError {
     print("Printer error: \(printerError).")
 } catch {
     print(error)
 }

使用 defer 代码块来表示在函数返回前,函数中最后执行的代码。无论函数是否会抛出错误,这段代码都将执 行。

var fridgeIsOpen = false
 let fridgeContent = ["milk", "eggs", "leftovers"]
 func fridgeContains(_ food: String) -> Bool {
     fridgeIsOpen = true
     defer {
         fridgeIsOpen = false
     }
     let result = fridgeContent.contains(food)
     return result
 }
 fridgeContains("banana")
 print(fridgeIsOpen)
  • 泛型:尖括号<>可创建泛型函数、方法、类、枚举和结构体
func repeatItem(repeating item: Item, numberOfTimes: Int) ->[Item] {
    var result = [Item]()
    for _ in 0..

你可能感兴趣的:(Swift 整理(一)——初探小海鸥)