Swift 中有 Object 类吗?

2023-12-28

我对斯威夫特很陌生。 Swift 中是否有像 Java/C# 中那样通用的包罗万象的 Object 类?

我可以声明一个可以容纳任何内容的数组(整数/字符串/字符...等)吗?


正如中所解释的“为什么 Swift 中没有通用基类?” https://stackoverflow.com/questions/24137368/why-is-there-no-universal-base-class-in-swift,不,但是有一个每个类型都隐式遵守的通用协议:Any.

// A statically typed `Any` constant, that points to a value which
// has a runtime type of `Int`
let something: Any = 5 

// An array of `Any` things
let things: [Any] = [1, "string", false]

for thing in things {
    switch thing {
    case let i as Int: consumeInt(i)
    case let s as String: consumeString(s)
    case let b as Bool: consumeBool(b)

    // Because `Any` really does mean ANY type, the compiler can't prove
    // that this switch is exhaustive, unless we have a `default`
    default: fatalError("Got an unexpected type!")
    }
}

然而,使用Any大多数时候都是不明智的。对于大多数目的,受歧视的联合是更好的选择,Swift 以枚举的形式提供了这种选择。这些确保考虑所有可能的类型:

// Using an enum with associated values creates a discriminated union
// containing the exact set of type that we wish to support, rather than `Any`
enum SomeValue { // Note: this is a bad name, but just as an example!
    case int(Int)
    case string(String)
    case bool(Bool)
}

let someValues: [SomeValue] = [.int(1), .string("string"), .bool(false)]

for value in someValues {
    switch value {
    case .int(let i): consumeInt(i)
    case .string(let s): consumeString(s)
    case .bool(let b): consumeBool(b)

    // Enums have finitely many cases, all of which we exhausted here
    // No `default` case required!
    }
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Swift 中有 Object 类吗? 的相关文章

随机推荐