如果使用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])
到SWIFT说:
<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。
我得到一个错误,“‘myStructType’不等同于‘任何’” – PopKernel 2015-01-31 18:43:18
你能张贴代码(或链接到它)? – 2015-01-31 18:44:59
当然。功能在这里:http://pastebin.com/cztjMbFW – PopKernel 2015-01-31 18:49:12