2

ObjectiveC Code:

CCButton *mNumTiles[10];

I Tried this Swift code but Crashing

var mNumTiles : [CCButton]! 

mNumTiles[0] = CCButton.buttonWithTitle(""

How to declare array of custom Class object in Swift ?

2
  • You merely declared the variable, but you didn't initialize it. Commented Apr 27, 2015 at 15:08
  • 1
    That's not Objective-C code, but rather plain old C code... I mean, it's not an NSArray but a C-style array. Commented Apr 27, 2015 at 15:12

4 Answers 4

9

You've declared an array but haven't initialized one.

You can do it like this:

var mNumTiles = [CCButton]()

mNumTiles.append(CCButton(title: ""))

Note that you don't have to declare the type of mNumTiles; Swift will infer it from the initialization ([CCButton]())

Sign up to request clarification or add additional context in comments.

2 Comments

still I got error for this answer, see this app.box.com/s/3fxu72z2l7rsz7ln6lt0gcmhdp1pcg47
@iPhoneChip That's because you typed something different than what I wrote. Change : to =.
4

Try this:

var mNumTiles : [CCButton] = []

Comments

3

You have to initialize the array:

var mNumTiles = [CCButton]()

And then you can append into it.

Comments

2

Your variable declaration is incorrect, because the variable is not initialized (nil). To do that, you have to construct an array like this

var mNumTiles : [CCButton]! = [CCButton](count: 10, repeatedValue: nil)

Another way to do it would be to initialize an empty array and use append to add the button:

var mNumTiles : [CCButton]! = []
mNumTiles.append(CCButton....)

You should make sure to read this if you want to learn more about arrays in Swift:

https://developer.apple.com/library/ios/documentation/General/Reference/SwiftStandardLibraryReference/Array.html

1 Comment

still getting compiler error for this answer see app.box.com/s/x8ytawnn9njzl2cuxkagwf7v96qdd5vi

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.