Skip to content

Instantly share code, notes, and snippets.

@worthmine
Last active August 29, 2015 14:13
Show Gist options
  • Save worthmine/9efb8c65b410a9eb0357 to your computer and use it in GitHub Desktop.
Save worthmine/9efb8c65b410a9eb0357 to your computer and use it in GitHub Desktop.
[Swift]型の違う値を同じ配列に入れる ref: http://qiita.com/worthmine/items/e1bde90f0fea60af3f9b
var arrayWithAnyType :[Any] = [/* You can insert here any initial values */]
var a :Array = ["String", "String2", "String3" ]
var b :Array = [4, 7, 8 ]
var c: [Any] = [a, b, 0]
c.shift() // -> ["String", "String2", "String3"]
class Foo {}
let aClass :Foo = Foo()
let anArray :Array = [0, 1, 2]
let anInt :Int = 0
// 普通にArray型であると明示的に示すと
var array :Array = ["String" ]
array.append(aClass) // Error "'Foo' is not convertible to 'String'"
array.append(anArray) // Error "'[Int]' is not convertible to 'String'"
array.append(anInt) // Error "'Int' is not convertible to 'String'"
// 上記全て怒られます
array.append("Another") // ->["String","Another"] //唯一怒られません
var arrayWithAnyType :[Any] = ["String"]
arrayWithAnyType.append(aClass) // -> ["String", Foo]
arrayWithAnyType.append(anArray) // -> ["String", Foo, [0, 1, 2]]
arrayWithAnyType.append(anInt) // -> ["String", Foo]
arrayWithAnyType.count // -> 4 // 3要素追加できてます
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment