如果你使用 Any 而不是 AnyObject 你可以传递任何类型,结构体也是如此:
class func countOfItemsInArray(array: [Any]?) -> Int
这有点奇怪。
我用过这个功能:
func countOfItemsInArray(array: [Any]?) -> Int {
return array != nil ? array!.count : 0
}
声明了两个 Assignment 结构并将它们放入一个数组中:
let structOne = Assignment(name: "1", dueDate: NSDate(), subject: "1")
let structTwo = Assignment(name: "2", dueDate: NSDate(), subject: "2")
let myArray: [Assignment] = [structOne, structTwo]
但这是有趣的部分。
调用println(countOfItemsInArray(myArray)) 时出现错误:
<stdin>:27:33: error: 'Assignment' is not identical to 'Any'
println(countOfItemsInArray(myArray))
^
<stdin>:17:26: note: in initialization of parameter 'array'
func countOfItemsInArray(array: [Any]?) -> Int {
^
所以我测试了myArray 是否属于[Any]:
println(myArray is [Any])
斯威夫特说:
<stdin>:25:17: error: 'Any' is not a subtype of 'Assignment'
println(myArray is [Any])
^
但是当我将 myArray 的类型注释更改为 [Any] 时,它可以工作:
let myArray: [Any] = [structOne, structTwo]
当简单地将文字传递给函数时,它也可以工作:
countOfItemsInArray([structOne, structTwo])
整个代码示例可见here。