How to declare array of custom Class object in Swift - iphone

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 ?

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]())

Try this:
var mNumTiles : [CCButton] = []

You have to initialize the array:
var mNumTiles = [CCButton]()
And then you can append into it.

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

Related

Why the fatal error: Array index out of range show when print array in Swift?

I am new in Swift. I create a node swift file to store the node information. And the other group swift file is a group which store the all node.
The code of Node.swift is like the following:
class Node {
var id:UInt8=0
var type:Int=0
var name:String=""
var bdAddr:NSUUID!
//The node private packet counter
var nodePktNum:Int=0
}
The code of Group.swift is like the following:
class Group {
var mLedDevice:[LedDevice]? = [LedDevice]()
class LedDevice {
var node :Node?
var rssi :Int?
}
func allocateNode()
{
print("mLedDevice![0].node = \(mLedDevice![0].node))")
}
}
When I try call function (allocateNode) and try to print mLedDevice![0].node) via print("mLedDevice![0].node = \(mLedDevice![0].node))")
It show the error fatal error: Array index out of range.
Did I missing something for initialize of var mLedDevice:[LedDevice]? = [LedDevice]() ?
Thanks in advance.
===================================EDIT=================================
I want to add the item into array , so I create a parameter like let let leddevice : LedDevice , and try to give it some value. And add the leddevice into array mLedDevice. But it show constant 'leddevice' used before being initialized.
How to give the init value for let leddevice : LedDevice ?
func allocateNode()
{
let leddevice : LedDevice
leddevice.node?.id = UInt8(0)
leddevice.node!.bdAddr = NodeUUID
mLedDevice?.append(leddevice)
}
The only thing I can think about that can cause this is that the array is empty i.e. you are attempting to access index 0 of that array but that doesn't exist.
Try the following and it may give you an insight on how to solve it after seeing the content of the array:
print("mLedDevice = \(mLedDevice))")
In other words you are instantiating an array with no elements in it.
In your line of code
var mLedDevice:[LedDevice]? = [LedDevice]()
You are only initializing an empty array. What you are trying afterwards is to access the first element, of an empty array, which is out of bounds.
Before your print statement, you will need to add an item to your array
var ledDevice = LedDevice()
mLedDevice.append(ledDevice)
And then your print statement would not give you any errors.
UPDATED: Answer for the added question
let leddevice : LedDevice is defining a constant of type LedDevice but is not yet initialized, and then it is being used in the next lines of code. You should replace it with
let leddevice = LedDevice()
Which will also initialize the variable.
Note: If you have any further questions, you should write a new question for that.
Note2: Have you read any guides about initialization?

Difference between various type of Variable declaration in swift

I am quite a confused when and how to declare variables in particular points in Swift and its causing a headache for a new guy like me in SWIFT.
What is the difference between the following type of declarations? I have given my thoughts and understanding on them. Please rectify me with your solution if I am wrong and be a bit explanatory so that I can know the actual and exact answer.
Array -
1) var arr = NSArray()//I think its an instance of immutable NSArray type
2) var arr = NSMutableArray()
3) var arr = Array()//I have no idea of difference between NSArray and Array type. Might be both are same
4) var arr : NSMutableArray?//Creates an optional type but how is it different from line no.2
5) var arr : NSMutableArray = []//creates an empty array NSMutableArray type and again how is it different from line no.2 & 3
Please clarify a bit clearly so that my confusion level would be a bit clear. Thanks
Array is a swift type where as NSArray is an objective C type. NS classes support dynamic-dispatch and technically are slightly slower to access than pure swift classes.
1) var arr = NSArray()
arr is an NSArray() here - you can re-assign things to arr but you can't change the contents of the NSArray() - this is a bad choice to use IMO because you've put an unusable array into the variable. I really can't think of a reason you would want to make this call.
2) var arr = NSMutableArray()
Here you have something usable. because the array is mutable you can add and remove items from it
3) var arr = Array()
This won't compile - but var arr = Array<Int>() will.
Array takes a generic element type ( as seen below)
public struct Array<Element> : CollectionType, MutableCollectionType, _DestructorSafeContainer {
/// Always zero, which is the index of the first element when non-empty.
public var startIndex: Int { get }
/// A "past-the-end" element index; the successor of the last valid
/// subscript argument.
public var endIndex: Int { get }
public subscript (index: Int) -> Element
public subscript (subRange: Range<Int>) -> ArraySlice<Element>
}
4) var arr : NSMutableArray?
You are defining an optional array here. This means that arr starts out with a value of nil and you an assign an array to it if you want later - or just keep it as nil. The advantage here is that in your class/struct you won't actually have to set a value for arr in your initializer
5) var arr : NSMutableArray = []
It sounds like you are hung up on confusion about Optional values.
Optional means it could be nil or it could not
When you type something as type? that means it is nil unless you assign it something, and as such you have to unwrap it to access the values and work with it.
#G.Abhisek at first about you question. var arr: NSMutableArray = [] and var arr = NSMutableArray() means the same. the first one means, i ask the compiler to create a variable of type NSMutableArray and initialize it as an empty NSMutableArray. the second one means, i ask the compiler to create a variable and assign to it an empty initialized NSMutableArray. in the second case the compiler has to infer the right type of the variable, in the first case i did it by myself. still, the result will be the same. var arr1: Array<AnyObject> = [] and var arr2: NSMutableArray = [] are totally different things!. arr1 srores value type Array, arr2 stores reference to the instance of an empty NSMutableArray class. you can write let arr2: NSMutableArray = [] and next you can add an object there ... but you are not able to do thinks like arr2 = ["a","b"]. arr2 is constant, not variable, so the value stored there is imutable.
i am again close to my computer ... in the code below, you can see the main differences between swift and foundation arrays
import Foundation
let arr1: NSMutableArray = []
arr1.addObject("a")
arr1.addObject(10)
arr1.forEach {
print($0, $0.dynamicType)
/*
a _NSContiguousString
10 __NSCFNumber
*/
}
var arr2: Array<Any> = []
arr2.append("a")
arr2.append(10)
arr2.forEach {
print($0, $0.dynamicType)
/*
a String
10 Int
*/
}
var arr3: Array<AnyObject> = []
arr3.append("a")
arr3.append(10)
arr3.forEach {
print($0, $0.dynamicType)
/*
a _NSContiguousString
10 __NSCFNumber
*/
}
print(arr1.dynamicType, arr2.dynamicType, arr3.dynamicType)
// __NSArrayM Array<protocol<>> Array<AnyObject>

Access Class In A Dictionary - Swift

I am now writing a program involves class and dictionaries. I wonder how could I access a class's values inside a dictionary. For the code below how do I access the test1 value using the dictionary. I have tried using dict[1].test1but it doesn't work.
class test {
var tes1 = 1
}
var refer = test()
var dict = [1:refer]
There are a few problems with the line dict[1].test1:
Firstly, the subscript on a dictionary returns an optional type because there may not be a value for the key. Therefore you need to check a value exists for that key.
Secondly, in your class Test you've defined a variable tes1, but you're asking for test1 from your Dictionary. This was possibly just a type-o though.
To solve these problems you're code should look something like this:
if let referFromDictionary = dict[1] {
prinln(referFromDictionary.test1)
}
That's because the subscript returns an optional, so you have to unwrap it - and the most straightforward way is by using optional chaining:
dict[1]?.tes1
but you can also use optional binding:
if let test = dict[1] {
let value = test.tes1
}

Howto reference an Array in swift

I would like to have a reference to an array for better coding, but I don't know howto do. The following code should illustrate what I mean:
I have a class, with an Array of Array of Objects as follow:
class Group: NSObject {
var alGroup = [[NSObject]]();
}
I have the following 2 different codes from which I would like to prefer using the first one.
code 1, which doesn't work with a reference to the inner array. With not working I mean the object is lost (no syntax or runtime error) :
func addObjectto_new_Group(o:NSObject, inout group:Group){
var alGroup = group.alGroup;
var alNew = [NSObject]();
alNew.append(o);
//group.alGroup.append(alNew);
alGroup.append(alNew);
}
Code 2, which works, but not preferred:
func addObjectto_new_Group(o:NSObject, inout group:Group){
//var alGroup = group.alGroup;
var alNew = [NSObject]();
alNew.append(o);
group.alGroup.append(alNew);
//alGroup.append(alNew);
}
How can I have a reference to an array like in code 1 ?
When you create your 'alias' variable var alGroup = group.alGroup you do not copy by reference, but by value as explained in the comments to your question. So one way to solve this is to use the full name like in group.alGroup.append(alNew).
However there is a another option which might be to your liking:
func addObjectToNewAlGroup(o:NSObject, inout alGroup : [[NSObject]])
{
var alNew = [NSObject]()
alNew.append(o)
alGroup.append(alNew)
}
var aGroup = Group()
addObjectto_new_Group("a1", &aGroup)
addObjectto_new_Group("b2", &aGroup)
addObjectToNewAlGroup("c3", &aGroup.alGroup)
This uses your 'Code 2' version, and a new function doing the same, but passing the array by reference into the function. This is legal, and does work. It is only references within a function which doesn't work as you want.

Append a class object to an array

I am having trouble with the syntax here. Basically I created a simple class and hoping to add the object of that class to an Array.
class simpleClass {
var aNum = Int()
var aWord = String()
init(thisNum:Int,thisString:String)
{
aNum = thisNum
aWord = thisString
}
}
var aObj:simpleClass
var aArray:Array<simpleClass>
aObj = simpleClass(thisNum:12,thisString:"Test")
aArray.append(aObj)
As you can see I have created an object of simpleClass and trying to append it to an array of type simpleClass. However, I receive an error saying
passed by reference before being initialized
I guess I must be missing something in the syntax. Hoping someone out there could point out my mistake.
thanks,
sweekim
You need to assign an array to the array variable.
var aArray:Array<simpleClass> = []
Or if you prefer,
var aArray = Array<simpleClass>()
Or even (my preference)
var aArray: [simpleClass] = []
Or
var aArray = [simpleClass]()
Better yet you could even reorder things and do this:
var aArray = [simpleClass(thisNum:12,thisString:"Test")]
instead of the whole 4 last lines.
Incidentally, you might find it better to declare your class like this:
class simpleClass {
var aNum: Int
var aWord: String
init(thisNum:Int,thisString:String) {
aNum = thisNum
aWord = thisString
}
}
This types aNum and aWord, but does not assign them values, since you then do that in the init method. The reason being, if you ever forgot to assign a value in init the compiler will warn you, whereas if you default them, it won’t. It’s fine to default them instead, but then don’t include them in an init method – one or the other is best, both is a bit redundant and can lead to mistakes.
Change this line:
var aArray:Array<simpleClass>
To this:
var aArray:Array<simpleClass> = []
You were declaring the array type but you forgot to make any array. If you actually look at the error message, it tells you exactly that - you didn't initialize the variable.
Also I think you didn't quite declare your instance of simpleClass correctly. I did this to silence the errors:
var aArray:Array<simpleClass> = []
let aObj:simpleClass = simpleClass(thisNum:12,thisString:"Test")
aArray.append(aObj)
Note the way an instance of simpleClass is created.