基本知识点

1.错误处理,抛错误,throw

enum PrinterError: Error {
    case OutOfPaper
    case NoToner
    case OnFire
}

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

//第1种处理方式
let a = try? send(job: 7, toPrinter: "Never Has Toner")
if a != nil {
    print("没有错误")
}

//第2种处理方式
do {
    let b = try send(job: 7, toPrinter: "Never Has Toner")
    print(b)
} catch {
    print(error)
}

//第3种处理方式
do {
    let printerResponse = try send(job: 1440, toPrinter: "Never Has Toner")
    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)
}

2.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)

3.类型别名

typealias AudioSample = UInt16
var maxAmplitudeFound = AudioSample.min // maxAmplitudeFound 现在是 0

4.枚举enum

enum LyNetWorkMethod {
    case post
    case get
}

enum LyNetWorkMethod {
    case post, get
}

5.元祖

func addName(name : String) -> (a : Int , b : String) {
    if name == "1" {
        return (9 , "1")
    }
    else {
        return (1 , "2")
    }
}

addName(name: "1").0
addName(name: "1").a

6.断言assert

let age = -3
assert(age >= 0, "A person's age cannot be less than zero")
// 因为 age < 0,所以断言会触发

7.运算符

//三目运算符
let k = 10 > 11 ? "yes" : "no"

//空合运算符
let defaultColorName = "red"
var userDefinedColorName: String? //默认值为 nil
var colorNameToUse = userDefinedColorName ?? defaultColorName
// userDefinedColorName 的值为空,所以 colorNameToUse 的值为 "red"

 8.检测 API 可用性 

if #available(iOS 10, macOS 10.12, *) {
    // 在 iOS 使用 iOS 10 的 API, 在 macOS 使用 macOS 10.12 的 API
} else {
    // 使用先前版本的 iOS 和 macOS 的 API
}

 

posted @ 2017-03-27 16:20  ZJea  阅读(116)  评论(0编辑  收藏  举报