示例工程 07-optionals
07-optionals/Sources/Ch07Kit/OptionalBasics.swift
/// Optional 是一个枚举:`.some(value)` 与 `.none`,不是「可能为空的指针」。
public struct Address: Sendable, Equatable {
public let city: String
public init(city: String) {
self.city = city
}
}
public struct User: Sendable, Equatable {
public let name: String
public let address: Address?
public init(name: String, address: Address?) {
self.name = name
self.address = address
}
}
public enum OptionalBasics {
public static func city(of user: User) -> String {
user.address?.city ?? "unknown"
}
public static func greeting(for user: User) -> String {
if let address = user.address, let city = Optional(address.city), !city.isEmpty {
return "\(user.name)@\(city)"
}
return "\(user.name)@?"
}
/// `guard let` 把失败路径前置,主逻辑保持一级缩进。
public static func normalized(_ raw: String?) -> String? {
guard let raw, !raw.isEmpty else {
return nil
}
return raw.lowercased()
}
/// Optional 也是值,可以比较、可以放进集合。
public static func describe(_ value: Int?) -> String {
switch value {
case .some(0):
return "some(0)"
case .some(let number):
return "some(\(number))"
case .none:
return "none"
}
}
}