抛出函数与捕获错误
Coddy 面向 C# 开发者的 Swift 课程的第 31 课,共 48 课。
C# 方法可以抛出异常,而不需要 throws 子句。Swift 使用 throws 标记会抛出异常的函数,并使用 try 标记可能抛出异常的调用方。调用方可以使用 do 和 catch 捕获错误,也可以从另一个会抛出异常的函数中继续向上传递错误,或者有意使用 try? 将失败转换为可选值。Swift 错误是遵循 Error 的值,不一定是异常类实例。示例会拒绝空标签,并返回去除首尾空白后的非空标签。不要机械地使用 try! 来压制编译器警告:如果调用抛出异常,程序就会触发陷阱。捕获你能处理的失败,并让调用方负责成功结果的格式化。
C#
完整程序文件:Program.cs。
using System;
using System.Collections.Generic;
using System.Linq;
static class Labels { public static string Clean(string value) { string s = value.Trim(); if (s.Length == 0) throw new ArgumentException(); return s; } }
class Program
{
static void Main()
{
foreach (string text in new[] { " ok ", " " }) {
try { Console.WriteLine(Labels.Clean(text)); }
catch (ArgumentException) { Console.WriteLine("empty"); }
}
}
}Swift
完整程序文件:LabelError.swift。
enum LabelError: Error { case empty }完整程序文件:Functions.swift。
import Foundation
func clean(_ value: String) throws -> String {
let text = value.trimmingCharacters(in: .whitespaces)
guard !text.isEmpty else { throw LabelError.empty }
return text
}完整程序文件:main.swift。
for text in [" ok ", " "] {
do { print(try clean(text)) }
catch LabelError.empty { print("empty") }
catch { print("other") }
}挑战
简单实现 DivisionError: Error,其中包含 case zero,并在 Functions.swift 中实现 quotient(_ numerator: Int, by denominator: Int) throws -> Int。当 denominator 为 0 时抛出 zero,否则使用向零截断的整数除法。输入包含两个介于 -1000 到 1000 之间的整数。输出商;捕获到此错误时,输出 zero。
实现所需的 API 和 solve(_ input: String) -> String。返回不带末尾换行符的输出文本;不要在可编辑代码中打印。锁定的驱动程序会使用其他有效输入独立检查这些 API,然后在返回的文本后准确打印一个换行符。所有数值运算都不会超出 Int 的范围。
你的代码写在 DivisionError.swift 和 Functions.swift 中。main.swift 包含提供的输入/输出代码,不能编辑。
亲手试试
import Foundation
func apiChecks(_ input: String) -> Bool {
do { guard try quotient(17, by: 4) == 4 else { return false }; do { _ = try quotient(2, by: 0); return false } catch DivisionError.zero { } catch { return false }; return try quotient(-17, by: 4) == -4 } catch { return false }
}
let input = String(data: FileHandle.standardInput.readDataToEndOfFile(), encoding: .utf8)!
// 开始公开 API 检测
let apiOK = apiChecks(input)
// 结束公开 API 检测
if apiOK { print(solve(input)) } else { print("API mismatch") }
这节课包含一个小测验。开始学习即可作答,并记录你的进度。
面向 C# 开发者的 Swift中的所有课
自己练习: Swift 在线编辑器