I cannot figure out how to add values to an empty array in Swift. I have tried started with empty array in two different ways:
var emptyArray : Int[]?
emptyArray = Int[]()
and
var emptyArray = []
(by the way, what is the difference with these two ways of creating empty arrays?)
I have tried to add an integer to the array with emptyArray.append(1), emptyArray += [1] but none works nor it is in the guide book (or maybe, it is hidden some where that I couldn't figure out). Both of these work if there is one or more values in it and this is driving me crazy! Please let me know how to if you know how to do it. Thank you!
First, create empty Int array:
var emptyArray : Int[] = []
or:
var emptyArray = Int[]()
Add number to that array (two ways):
emptyArray += [1]
emptyArray.append(2)
Array now contains [1, 2]
You need to first declare the empty array in Swift like this:
var emptyArray = [Int]()
You can then append that array with whatever value/variable you so choose like this:
emptyArray.append(6)
just be sure you keep in mind that trying to append a type that mismatches your array declaration will give you a compile error. For example, trying to append a string would error since this array was declared using the Int type.
Playgrounds in XCode are an excellent resource for testing things like this.
Swift
var arrName = [String]()
arrName = ["Deep", "Hemant", "Yash"]
print("old array--> ", arrName)
arrName.append("Jay")
print("new array--> ", arrName)
Output:-
old array--> ["Deep", "Hemant", "Yash"]
new array--> ["Deep", "Hemant", "Yash", "Jay"]
Related
I have a array
arr=['a','b','c']
and a variable
var='a'
I am trying to remove the variable from array and append the resultant array to a new array.
newarray = []
if var in arr:
newarray.append(arr.remove(var))
print(newarray)
This does not print anything. However when I run only arr.remove(var) it works...I am not able to append the resultant smaller array to a new variable.
From your description, this is what you may be looking for:
arr = ['a','b','c']
var = 'a'
newarray = []
if var in arr:
arr.remove(var)
newarray.append(arr)
print(newarray)
Output:
[['b', 'c']]
Note the output of following:
if var in arr:
print(arr.remove(var))
print(newarray.append(arr))
print(newarray)
Output:
None
None
[['b', 'c']]
arr.remove(var) and newarray.append(arr) work on list in place but do not return anything.
Hence newarray.append(arr.remove(var)) means newarray.append(None)
use pop() function instead. Change:
newarray.append(var)
print(arr.remove(var))
to:
newarray.append(arr.pop(0))
print(newarr)
Looks like your code got a bit mangled. Here's how to fix it:
arr = ['a','b','c']
var = 'a'
newarray = []
if var in arr:
newarray.append(var)
arr.remove(var)
print(newarray)
To understand why your original code printed [None], you first need to understand array.remove(). array.remove is a void function: it does not return a value, only performs tasks. If you try to get or call its return value in a function such as array.append(), Python doesn't know how to react and returns None. The None value was then appended to the array properly by the array.append() function.
I found these answers:
Sort an array of tuples in swift 3
How to sort an Array of Tuples?
But I'm still having issues. Here is my code:
var countsForLetter:[(count:Int, letter:Character)] = []
...
countsForLetter.sorted(by: {$0.count < $1.count})
Swift 3 wanted me to add the by: and now it says that the result of the call to sorted:by is unused.
I'm new to swift 3. Sorry if this is a basic question.
You are getting that warning because sorted(by... returns a new, sorted version of the array you call it on. So the warning is pointing out the fact that you're not assigning it to a variable or anything. You could say:
countsForLetter = countsForLetter.sorted(by: {$0.count < $1.count})
I suspect that you're trying to "sort in place", so in that case you could change sorted(by to sort(by and it would just sort countsForLetter and leave it assigned to the same variable.
Sorted() returns a new array, it does not sort in place.
you can use :
countsForLetter = countsForLetter.sorted(by: {$0.count < $1.count})
or
countsForLetter.sort(by: {$0.count < $1.count})
I'm having trouble adding an existing array to the beginning of another array.
For example:
MutableID array contains 1,2,3,4,5 & idArray array contains 6,7,8
self.MutableID.addObjectsFromArray(idArray as [AnyObject])
//currently puts values to the end of the array not the beginning
this code outputs 1,2,3,4,5,6,7,8 but I want it to output 6,7,8,1,2,3,4,5
I need the values added to the beginning of self.MutableID Any suggestions on how I can accomplish this?
NSMutableArray has insertObjects method.
self.MutableID.insertObjects(otherArray as [AnyObject], atIndexes: NSIndexSet(indexesInRange: NSMakeRange(0, otherArray.count)))
Or you can assign the mutable array to a swift array and use insertContentsOf method ;)
self.MutableID = NSMutableArray(array: [1,2,3,4])
var otherArray = NSMutableArray(array: [6,7,8,9])
var swiftArr : [AnyObject] = self.MutableID as [AnyObject]
swiftArr.insertContentsOf(otherArray as [AnyObject], at: 0)
self.MutableID.insertContentsOf(idArray as [AnyObject], at: 0)
This question is the Swift version of this question which solves the problem in Objective-C.
If we must, for whatever reason, be using Objective-C's NSArray or NSMutableArray, then we can simply use a Swift translation of the code in my answer over there:
let range = NSMakeRange(0, newArray.count)
let indexes = NSIndexSet(indexesInRange: range)
oldArray.insertObjects(newArray as [AnyObject], atIndexes: indexes)
Where oldArray is an NSMutableArray and newArray is NSArray or NSMutableArray.
Or the other approach, append and reassign:
oldArray = newArray.arrayByAddingObjectsFromArray(oldArray as [AnyObject])
But the most correct thing to do would be to use the Swift Array type, and then use the insertContentsOf(_: Array, at: Int) method, as fluidsonic's answer describes.
for example:
let myArray:[] = []
or
let myArray = []
The first one is not possible (it will complain about expected element type) If you don't know the element type you can use AnyObject but if you know the type of it you have to put it there (Int,Double,String, AnyObject, etc...).
var myArrayOfDoubles:[Double] = []
The second one (when omitting the type) is OK ONLY if you initialize it with some values but If you try it with an empty array you won't be able to append anything (at least using Playground) saying that NSArray does not have a member named append.
var myArrayOfInts = [1,2,3,4,5] // [Int]
var myArrayOfAnyObject:[AnyObject] = [] // [AnyObject]
And finally last but not least you have to define it as var because if you define it using let it will stay empty forever :)
Yes, you can, it can be Any or Anyobject...
example:
var noTypeArray = [Any]()
If you want to fill the array eventually it may be var, no let, there's no point otherwise.
No. If you don't know what will go in use this:
var myArray = [Any]()
Apple has introduced a Type-GeStaPo and you must type anything that's not up the tree at count three.
To add to this use
myArray.append("this")
myArray.append(1)
myArray.append(myObject)
Just started using Swift and I'm getting pissed at a few elements. First is that most standard stuff are structs rather than objects, which means they're passed in as values rather than pointers as I'm used to. The other thing is that using the optional element system is really annoying.
If I am trying to declare an array without putting anything in it, I declare it like this:
var theArray : [Int]
In order to put anything in it, I would declare it like this:
var theArray : [Int]?
Then add objects as follows:
theArray[someIndex] = someInt
//or
theArray.append(someInt)
However, I get an error. In Java, I could have just initialized an array with a length, which would have given me an a fixed-size array with all 0's.
The problem, summarized in a sentence, is adding elements to Swift arrays that have been initialized without values. How do you do this?
In order to initialize an empty array use:
var theArray : [Int] = []
then add elements by using append method. What you currently did is that you just declared it in the first case non optional and in the second case as an optional variable typed as int array without initializing it.
If you want the array to contain Int types, of course there are many ways to declare that, based on implicit or explicit type inference. These are all valid declarations of an array containing Int types
var array1 = [Int]()
var array2: [Int] = []
var array3 = Array<Int>()
var array4: Array<Int> = []
If you want an array of a certain size, with the values initialized to a certain value you can use, in this example you'll get an Array<Int> with 5 elements, all initialised to 0
var array = Array(count: 5, repeatedValue: Int(0))
Here you go:
var theArray = Array(count:[the length you want], repeatedValue:Int(0))
This will replicate the Java behaviour.