Menu
CoddyTech

Result 作为已存储的结果

Coddy 面向 C# 开发者的 Swift 课程的第 32 课,共 48 课。

Swift 的 Result<Success, Failure> 会将成功或失败存储为普通值;其中的失败类型必须遵循 Error。当你需要保留结果或将其传递下去,而不是立即抛出错误时,这种方式很有用。对于类似的 API,C# 通常会使用自定义结果类,或使用带输出参数的 Try 方法;这些约定并不自动等同于 Swift 的 Result。这里的查找操作会返回已存储的颜色标签,或者返回键缺失错误。模式匹配会提取关联的成功值。在你选择诸如 get() 这样会抛出错误的操作之前,失败仍然只是一个值。请将查找失败与成功返回空字符串区分开来。

C#

完整程序文件:Program.cs。

using System;
using System.Collections.Generic;
using System.Linq;
sealed class Lookup { public bool Success { get; private set; } public string Value { get; private set; } public Lookup(bool success, string value) { Success = success; Value = value; } }
static class Palette { public static Lookup Find(string key) { return key == "sky" ? new Lookup(true, "blue") : new Lookup(false, ""); } }

class Program
{
    static void Main()
    {
        var outcome = Palette.Find("sky");
        Console.WriteLine(outcome.Success ? outcome.Value : "missing");
    }
}

Swift

完整程序文件:LookupError.swift。

enum LookupError: Error { case missing }

完整程序文件:Functions.swift。

func findColor(_ key: String) -> Result<String, LookupError> {
    key == "sky" ? .success("blue") : .failure(.missing)
}

完整程序文件:main.swift。

let outcome = findColor("sky")
switch outcome {
case .success(let value): print(value)
case .failure(.missing): print("missing")
}
challenge icon

挑战

简单

实现 ParseError: Error,其中包含 case invalid,并实现 positive(_ text: String) -> Result<Int, ParseError>。只有解析出的整数严格大于零时才返回成功,否则返回 invalid 失败。输入是一个由 1 到 8 个数字或字母组成的 ASCII 字符串,也可以以减号开头。输出 ok:value 或 error。数值都能放入 Int。

实现所需的 API 和 solve(_ input: String) -> String。返回不带末尾换行符的输出文本;不要在可编辑代码中打印。锁定的驱动程序会用其他有效输入独立检查这些 API,然后恰好在返回的文本后打印一个换行符。所有数值运算都保持在 Int 的范围内。

你的代码应写在 ParseError.swift、Functions.swift 中。main.swift 包含提供的输入/输出代码,不能编辑。

亲手试试

import Foundation
func apiChecks(_ input: String) -> Bool {
guard case .success(23) = positive("23"), case .failure(.invalid) = positive("0"), case .failure = positive("bad") else { return false }; return true
}
let input = String(data: FileHandle.standardInput.readDataToEndOfFile(), encoding: .utf8)!
// 开始公开 API 检查
let apiOK = apiChecks(input)
// 结束公开 API 检查
if apiOK { print(solve(input)) } else { print("API mismatch") }
quiz icon自我测试

这节课包含一个小测验。开始学习即可作答,并记录你的进度。

面向 C# 开发者的 Swift中的所有课

自己练习: Swift 在线编辑器