Swift笔记 - 10.自定义错误、try?、try!、rethrows、defer、泛型、关联类
Swift笔记 - 10.自定义错误、try?、try!、rethrows、defer、泛型、关联类型、类型约束、可选项本质
自定义错误
- Swift中可以通过Error协议自定义运行时的错误信息
enum SomeError: Error { case illegalArg(String) case outofBounds(Int, Int) case outofMemory }
- 函数内部通过
throw
抛出自定义Error
,可能会抛出Error
的函数必须加上throws
声明
func divide(_ num1: Int, _ num2: Int) throws->Int {
if num2 == 0 {
throw SomeError.illegalArg("0不能作为除数")
}
return num1 / num2
}
- 需要使用
try
调用可能会抛出Error
的函数
var result = try divide(20, 10)
使用do-cath捕捉Error
- 可以使用do-catch捕捉Error
func test() {
print("1")
do {
print("2")
print(try divide(20, 0))
print("3")
} catch let SomeError.illegalArg(msg) {
print("参数异常:", msg)
} catch let SomeError.outofBounds(size, index) {
print("下标越界:", "size=\(size)", "index=\(index)")
} catch SomeError.outOfMemory {
print("内存溢出")
} catch {
print("其他错误")
}
print("4")
}
test()
// 1
// 2
//参数异常:0不能作为除数
//4
- 抛出
Error
后,try
下一句直到作用域结束的代码都将停止运行
处理Error
- 处理
Error
的2种方式- 通过
do-catch
捕捉Error
- 不捕捉
Error
,在当前函数增加throws
声明,Error
将自动拋给上层函数- 如果最顶层函数(
main
函数)依然没有捕捉Error
,那么程序将终止
- 如果最顶层函数(
- 通过
func test() throws {
print("1")
print(try divide(20, 0))
print("2")
}
try test()
// 1
// Fatal error: Error raised at top level
do {
print(try divide(20, 0))
} catch is SomeError {
print("SomeError")
}
func test() throws {
print("1")
do {
print ("2")
print(try divide(20, 0))
print("3")
} catch let error as SomeError {
print(error)
}
print("4")
}
try test()
// 1
// 2
//illegalArg("0不能作为除数…)
//4
try?、try!
- 可以使用
try?
、try!
调用可能会抛出Error
的西数,这样就不用去处理Error
func test() {
print("1")
var result1 = try? divide(20, 10) // Optional (2), Int?
var result = try? divide(20, 0) // nil
var result3 = try! divide(20, 10) // 2, Int
print("2")
}
test()
- a、b是等价的
var a = try? divide(20, 0)
var b: Int?
do {
b = try divide(20, 0)
} catch {}
rethrows
rethrows
表明:函数本身不会抛出错误,但调用闭包参数抛出错误,那么它会将错误向上抛func exec(_ fn: (Int, Int) throws -> Int, num1: Int, num2: Int) rethrows { print(try fn(num1, num2)) } // Fatal error: Error raised at top level try exec(divide, 20, 0)
defer做收尾工作
defer
语句:用来定义以任何方式(抛错误、return
等)离开代码块前必须要执行的代码defer
语句将延迟至当前作用域结束之前执行
func open(_ filename: String) -> Int {
print ("open")
return 0
}
func close( file: Int) {
print("close")
}
func processFile(_ filename: String) throws {
let file = open(filename)
defer {
close(file)
}
// tAfile
//...
try divide(20, 0)
//close将会在这里调用
}
try processFile("test.txt")
// open
// close
// Fatal error: Error raised at top level
泛型
- 泛型可以将类型参数化,提高代码复用率,减少代码量
func swapValues<T>(_ a: inout T, b: inout T){
(a, b) = (b, a)
}
var i1 = 10
var i2 = 20
swapValues(&i1, &i2)
var d1 = 10.0
var d2 = 20.0
swapValues(&d1, &d2)
struct Date {
var year = 0, month = 0, day = 0
}
var dd1 = Date(year: 2011, month: 9, day: 10)
var dd2 = Date(year: 2012, month: 10, day: 11)
swapValues(&dd1, &dd2)
- 泛型函数赋值给变量
func test<T1, T2>(_ t1: T1, _ t2: T2)()
var fn: (Int, Double) -> () = test
关联类型
- 关联类型的作用:给协议中用到的类型定义一个占位名称
- 协议中可以拥有多个关联类型
protocol Stackable {
associatedtype Element //关联类型
mutating func push(_ element: Element)
mutating func pop() -> Element
func top() -> Element
func size() -> Int
}
class Stack<E> : Stackable {
// typealias Element = E
var elements = [E](https://luowei.github.io/list/)
func push(_ element: E) { elements.append(element) }
func pop() -> E { elements.removeLast() }
func top() -> E { elements.last! }
func size() -> Int { elements.count }
}
class Stringstack: Stackable {
//给关联类型设定真实类型
// typealias Element = String
var elements = [String](https://luowei.github.io/list/)
func push(_ element: String) { elements.append(element) }
func pop() -> String { elements.removeLast() }
func top() -> String { elements.last! }
func size() -> Int { elements.count }
}
var ss = StringStack()
ss.push("Jack")
ss.push("Rose")
类型约束
protocol Runnable { }
class Person { }
func swapValues<T: Person & Runnable>(_ a: inout T, _ b: inout T) {
(a, b) = (b, a)
}
protocol Stackable {
associatedtype Element: Equatable
}
class Stack<E: Equatable>: Stackable {}
func equal<S1: Stackable, S2: Stackable>(_ s1: S1, _ S2: S2) -> Bool
where S1.Element == S2.Element, S1.Element: Hashable {
return false
}
var stack1 = Stack<Int>()
var stack2 = Stack<String>()
// error: requires the types 'Int' and 'String' be equivalent
equal(stack1, stack2)
协议中有关联类型 - 注意点
protocol Runnable {}
class Person : Runnable {}
class Car : Runnable {}
func get (_ type: Int) -> Runnable {
if type == 0 {
return Person()
}
return Car()
}
var r1 = get(0)
var r2 = get(1)
- 如果协议中有
associatedtype
protocol Runnable {
associatedtype Speed
var speed: Speed { get }
}
class Person: Runnable {
var speed: Double { 0.0 }
}
class Car: Runnable {
var speed: Int{ 0 }
}
两种解决方案: 1.泛型解决;2.不透明类型(some关键字)
func get<T : Runnable> (_ type: Int) -> T {
if type == 0 {
return Person() as! T
}
return Car() as! T
}
func get (_ type: Int) -> some Runnable {
return Car()
}
some
除了用在返回值类型上,一般还可以用在属性类型上
protocol Runnable { associatedtype Speed }
class Dog: Runnable { typealias Speed = Double }
class Person {
var pet: some Runnable {
return Dog()
}
}
可选项的本质
- 可选项的本质是enum类型
public enum Optional<Wrapped> : ExpressibleByNilLiteral {
case none
case some (Wrapped)
public init(_ some: Wrapped)
}
var age: Int? = 10
var age0: Optional<Int> = Optional<Int>.some(10)
var age1: Optional = .some(10)
var age2 = Optional.some (10)
var age3 = Optional(10)
age = nil
age3 = .none
var age: Int? = nil
var age0 = Optional<Int>.none
var age1: Optional<Int> =.none
var age: Int? = .none
age = 10
age = .some(20)
age = nil
switch age {
case let v?:
print("some", v)
case nil:
print("none")
}
switch age {
case let .some(v):
print ("some", v)
case .none:
print ("none")
}
var age_: Int? = 10
var age: Int?? = age_
age = nil
var age0 = Optional.some(Optional.some(10))
age0 = . none
var age1: Optional<Optional> = .some(.some(10))
age1 = .none
var age: Int?? = 10
var age0: Optional<Optional> = 10