Hi,
Today i hit a strange behaviour with Swift arrays. If I declare an array with the type Array<AnyObject> and try yo 'append' an Int value Swift return an error, what it's fine because Int is not an object. But if I import Foundation the 'append' wraps the Int in an NSNumber and what was failing before now work.
Here is the output from the Swift REPL:
➜ ~ swift
Welcome to Swift version 1.2. Type :help for assistance.
//Create an array of AnyObject
1> var array = [AnyObject]()
array: [AnyObject] = 0 values
//Now try to append an Int give the expected result
2> array.append(1)
repl.swift:2:7: error: cannot invoke 'append' with an argument list of type '(Int)'
array.append(1)
^
//Now import foundation and try again result in the expected error
2> import Foundation
3> array.append(1)
repl.swift:3:7: error: cannot invoke 'append' with an argument list of type '(Int)'
array.append(1)
^
//Try with a new array, just in case...
3> var secondArray = [AnyObject]()
secondArray: [AnyObject] = 0 values
4> secondArray.append(1)
repl.swift:4:13: error: cannot invoke 'append' with an argument list of type '(Int)'
secondArray.append(1)
^
//Restart the REPL
4> :quit
➜ ~ swift
Welcome to Swift version 1.2. Type :help for assistance.
//First import Foundation
1> import Foundation
2> var array = [AnyObject]()
array: [AnyObject] = 0 values
//Now it doesn't fail
3> array.append(1)
//And the Int is an "kind of" NSNumber
4> array[0].isKindOfClass(NSNumber.self)
$R0: Bool = true
I understand that in this case it's kind of not a big deal because NSNumber has value semantics, but I was not expecting this. If you stress this idea you find some inconsistencies at some point like if you have a function expecting an Int, for example:
➜ ~ swift
Welcome to Swift version 1.2. Type :help for assistance.
1> import Foundation
2> var array = [AnyObject]()
array: [AnyObject] = 0 values
3> array.append(1)
4> func expect_an_int(x : Int) -> Int {
5. return Int(12) + x
6. }
7> expect_an_int(array[0])
repl.swift:7:1: error: cannot invoke 'expect_an_int' with an argument list of type '((AnyObject))'
expect_an_int(array[0])
^
repl.swift:7:15: note: expected an argument list of type '(Int)'
expect_an_int(array[0])
^
7> array.append(Int(2))
8> array
$R0: [AnyObject] = 2 values {
[0] = Int64(1)
[1] = Int64(2)
}
9> array[0].isKindOfClass(NSNumber.self)
$R1: Bool = true
10> array[1].isKindOfClass(NSNumber.self)
$R2: Bool = true
Any thoughts?