如果使用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