Reputation: 555
I'm working to convert an iOS Obj-C project to Swift a class at a time. One Obj-C class involved the creation of an NSArray with even elements descriptive NSStrings and odd elements NSNumbers. Not a great piece of design in retrospect but perfectly valid and it did the job. I've converted this to Swift:
let coins = ["1p", 0.01 , "2p" , 0.02 , "5p" , 0.05 , "10p" , 0.10 , "20p" , 0.20 , "50p" , 0.50 , "99p" , 0.99 , "£1" , 1.00 , "£2" , 2.00 , "£5" , 5.00 , "£9.99" , 9.99 , "£10" , 10.00 , "£20" , 20.00]
I do realise that Swift enforces a single type in a one-dimensional array, so we wouldn't so much be talking an array of multiple types as an array of a flexible type - I expected it would infer AnyObject.
I never got to find out however, because it seems this line is an Xcode killer. In my overall project it causes indexing to hang, quickly becoming unresponsive and eventually consuming all system memory. Even this single line of code pasted into the init of a UIView subclass added to a blank single view application causes Xcode to hang on attempting to build in a similar fashion (i'm curious if others have the same experience).
Is there any legitimacy to what i'm attempting here, given that it is compilable code. If so, have I stumbled upon a Swift bug, or perhaps failed to do something vital to allow this to work. I can obviously find a far better way to go about doing what I want, particularly in Swift, but I don't think arrays of multiple types are so rarely seen in Obj-C that this isn't worth understanding further.
Upvotes: 2
Views: 3646
Reputation: 11868
Since e.g. Int is a struct instance and not an class instance the type is Any[]
var x : Any[] = [1,"2",3.0]
Upvotes: 1
Reputation: 3524
Looks like you've run into a bug in Xcode/Swift with Array<AnyObject>
and literals. I get the same result. Seems to get exponentially worse the more elements I add (my RAM gets full after ~6 elements). As a workaround, it seems to work fine to create a mutable array (using var
instead of let
) and adding the elements one by one. Janky without a doubt, but it doesn't crash Xcode.
var coins: Array<AnyObject> = []
coins += "1p"
coins += 0.01
coins += "2p"
coins += 0.02
coins += "5p"
coins += 0.05
coins += "10p"
coins += 0.10
coins += "20p"
coins += 0.20
coins += "50p"
coins += 0.50
coins += "99p"
coins += 0.99
coins += "£1"
coins += 1.00
coins += "£2"
coins += 2.00
coins += "£5"
coins += 5.00
coins += "£9.99"
coins += 9.99
coins += "£10"
coins += 10.00
coins += "£20"
coins += 20.00
Upvotes: 2