Creating and populating an empty Array - ios

I'm actually learning swift in order to develop iOS apps. I'd like, as an exercise, to create and populate an empty array, that would be filled by using a textfield and a button on the storyboard.
var arr = []
// When button is pressed :
arr.append(textfield.text)
XCode tells me that the append method is not a method of NSArray. So I have used the addObject one, but it is still not correct as the arr variable contains nil.
So here are my three questions :
Is it possible to create an empty array, and if so, how to populate it ?
Sometimes, in my ViewController, when I create a non-empty array, the append method is apparently not valid, and I don't understand why..
Finally, why even though I use the syntax :
var arr = [1] // For example
The arr object is NSArray object and not a NSMutableArray object, making it impossible to add/remove any object that is contained in it?
I hope my questions are clear, if not I'll upload more code of what I'm trying to build,
thank you for your answers !

Try to define your array as a String array, like this:
var arr: [String] = []
And then append to your list, either by:
arr.append("the string")
or
arr += ["the string"]

Empty array can be created using the following syntax.
var emptyArray = [String]()
emptyArray.append("Hi")
see this
You can use following also to add elements to your array.
//append - to add only one element
emptyArray.append("Hi")
//To add multiple elements
emptyArray += ["Hello", "How r u"]
emptyArray.extend(["am fine", "How r u"])
//Insert at specific index
emptyArray.insert("Who r u", atIndex: 1)
//To insert another array objects
var array1 = ["who", "what", "why"]
emptyArray.splice(array1, atIndex: 1)

Related

Why <Element> is not needed when creating default value array in Swift?

The code below is excerpted from The Swift Programming Language (Swift 4.2) of Apple documentation.
Now consider this: there are 3 ways to create an empty array in Swift.
First:
var list1 = Array<String>()
Second:
var list2: [String] = []
Third:
var list3 = [String]()
In order to create a default value array, we make use of repeating: and count:
var list4 = Array(repeating: "Apples", count: 3)
The above array is created using the first form of array creation, however, why it is not needed to declare the <Element> next to Array initializer.
Trying to create a normal empty array without specifying which type inside the <Element> would trigger a runtime error.
var list5 = Array("Apples") //A,p,p,l,e,s
var list6 = Array("Apples", "Oranges") //return an error
Why this happens?
Because it knows the type of the first item. Since Arrays only contain objects of a single type, of it can get that information from the first item, then it is enough.
Following your comment:
I think you are getting confused with the first item. "Oranges" is an array of [Character] so when you use Array("Oranges") you are creating an array of characters. For your third item, rather than passing in two values, which an Array doesn't know how to deal with, pass in an array like this: let list6 = Array(["Apples", "Oranges"])

Multidimensional Array Looping in cellForRowAtIndexPath Swift

I have a multidimensional array that I want to display the values of onto one UILabel in each respective cell.
My arrays look like this:
var arrayExample = [["beverages", "food", "suppliers"]["other stuff, "medicine"]]
I'm looping through these values in the cellForRowAtIndexPath in order for it to display on different cells (on a UILabel) the appropriate values:
if let onTheLabel: AnyObject = arrayOfContactsFound as? AnyObject {
for var i = 0; i < objects!.count; i++ {
cell?.contactsUserHas.text = "\(onTheLabel[indexPath.row][i])" as! String
print("arrayOfContactsFound Printing! \(onTheLabel)")
}
}
When printing to the console I get:
arrayOfContactsFound Printing! (
(
beverages,
"supply chain",
pharmacuticals
)
)
But on my label I get "beverages". That's it. How can I get the other 2 values (or X amount if there are more or less than 3 values)?
My for in loop is obviously not doing the trick. Assuming I can optimize/fix that to display all the values?
Thanks in advance.
In your loop you're setting the text of your label multiple times. Each time you set it it doesn't accumulate, it completely replaces the current text with the new text. You'll want something like this:
// Remove the cast and the loop in your code example, and replace with this
let items = arrayOfContactsFound[indexPath.row]
let itemsString = items.joinWithSeparator(" ")
cell?.contactsUserHas.text = itemsString
Another thing to note is your cast doesn't quite make a lot of sense.
var arrayExample = [["beverages", "food", "suppliers"]["other stuff, "medicine"]]
So arrayExample is of type [[String]]. I'm assuming each cell in your table view represents one of the arrays of strings in your array. So each cell represents one [String]. So your items should be arrayExample[indexPath.row]. The cast to AnyObject doesn't make too much sense. If anything you'd be casting it to [[AnyObject]], but there's no reason to because the compiler should already know it's [[String]].

How can NSMutableArray add object using let in swift

I created a NSMutableArray in swift using let and
when I add addObject in the mutableArray then it will add it even though I
used the let to assign a constant. Can anyone explain how let works in swift? If it doesn't allow you to add value in later then how is the following
code working?
let arr : NSMutableArray = [1,2,3,4,5]
arr.addObject(6)
println(arr)
Classes are reference types, and NSMutableArray is a class.
Foundation's NSMutableArray is different from Swift's Array: the latter is a value type.
If you create a constant NSMutableArray:
let ns: NSMutableArray = ["a", "b"]
then this works:
ns.addObject("c")
but this doesn't:
ns = ["d", "e"] // nope!
because you can change the content of the reference but you can't change what is assigned to the constant.
On the other hand, with Swift's Array:
let sw: [String] = ["a", "b"]
the constant can't be changed because it's a value, not a reference.
sw.append("c") // nope!
Doc: Structures and Enumerations Are Value Types and Classes Are Reference Types
disclaimer: this answer only applies to NS type data structures, please see #Eric D's answer for the full picture
let when used with a class just means the variable cant be changed, eg, to another array. If you dont want the array to be editable, use a normal NSArray and not a mutable one
let arr : NSMutableArray = [1,2,3,4,5]
arr = [1,2,3,4,5] //error trying to assign to a let variable that has already been assigned
arr.addObject(6) //fine because we are not changing what is assigned to arr, but we are allowed to change the object that is assigned to arr itself
I think your understanding of what a constant variable is, is a bit too strict.

Remove objects from an array before calling the API

I'm creating a table view which is hooked to an API. However, I'm having trouble with doing a refresh on pull. I've added the logic, however I can't seem to delete all the objects in the array before making a new api call.
Here is my array
var recentArray = Array<News>()
UIRefreshControl function:
func refresh(sender: UIRefreshControl){
lastObjectIndex=0
// remove all objects
getRecent()
self.tableVIew.reloadData()
self.refreshControl?.endRefreshing()
}
How can i remove all objects in my array before calling getRecent, which adds an object to the array?
You can reset your array like this:
recentArray = []
The compiler already knows the type of the array objects, so there's no need to do anything else.
You can remove all objects by calling
recentArray.removeAll(keepCapacity: false)
You can removed all object by adding following code befor getRecent called.
var array = [0, 1, 2, 3]
array.removeAll()
let count = array.count
// count is 0
Hope this will help you.

componentsSeparatedByString method in Swift

I had some troubles last night accessing the elements of an array created via the componentsSeparatedByStringMethod. My goal is to extract some information from an url content variable.
var arr = urlContent.componentsSeparatedByString("<span class=\"Some HTML class\">")
I printed arr to the log, it works perfectly
I'd like to access the second element of the array arr, in order to get the info I need (the information right after the span tag). I thought:
var info = arr[1]
would work, but it doesn't. I get an error message saying that the subscript method doesn't work for an object of type "AnyObject" or something similar. So the problem is arr is not an Array Object type but an AnyObject type. I tried to convert it to an array but it didn't work either.
Could anybody help through this little trouble? :)
In xcode 6.1.1 componentsSeperatedByString method returns [AnyObject]. You have to cast it to [String] like so:
if let arr = urlContent.componentsSeparatedByString("<span class=\"Some HTML class\">") as? [String] {
// arr is now [Sstring]
}
In xcode 6.3 beta this method returns [String] so cast is not needed.

Resources