Da REPL
xcrun swift
1> import Foundation
2> var test = ["a", "b", true, "hi", 1]
test: __NSArrayI = @"5 objects" {
[0] = "a"
[1] = "b"
[2] =
[3] = "hi"
[4] = (long)1
}
3>
potete vedere test
è NSArray
, che è una specie di AnyObject[]
o NSObject[]
Cosa succede è che Foundation
fornisce la capacità di convertire il numero e boolean in NSNumber
. Il compilatore eseguirà la conversione ogni volta che è necessario per compilare il codice.
Così ora hanno tipo comune di NSObject
e quindi dedurre come NSArray
Il codice non viene compilato in REPL senza import Foundation
.
var test = ["a", "b", true, "hi", 1]
<REPL>:1:12: error: cannot convert the expression's type 'Array' to type 'ArrayLiteralConvertible'
var test:Array = ["a", "b", true, "hi", 1]
<REPL>:4:18: error: cannot convert the expression's type 'Array' to type 'ExtendedGraphemeClusterLiteralConvertible'
ma si può fare questo
var test : Any[] = ["a", "b", true, "hi", 1]
Perché hanno un tipo comune, che è Any
.
Nota: AnyObject[]
non funziona senza import Foundation
.
var test:AnyObject[] = ["a", "b", true, "hi", 1]
<REPL>:2:24: error: type 'Bool' does not conform to protocol 'AnyObject'
Intendi ANYOBJECT? – Boon
AnyObject è il tipo – juniperi
Esiste un modo per verificare il tipo inferito di un array? – Boon