我对Swift很新。在Java / C#中是否存在Swift中的通用无所不包的Object类?
我可以声明一个可以容纳任何东西的数组(Int / String / Character ......等)吗?
答案 0 :(得分:4)
正如"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以enums的形式提供。这些确保考虑所有可能的类型:
// 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!
}
}
答案 1 :(得分:2)
您搜索的内容似乎有Any
和AnyObject
类型。您无法扩展它们,但您可以将任何对象强制转换为AnyObject
类型并插入[AnyObject]
数组。 Any
更广泛,包括Int
,String
,Bool
等。
答案 2 :(得分:0)
不,Swift没有通用的Object Class。