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.
Related
I'm new to coding and this is my first post!
I have created a dictionary in Swift where each individual value is an array.
Ex
1: [0.0443, 0.220832, 0.526799, 0.72147, 0.646954,0.511456,1.00405]
What I need to do is to access the value and store into a different array for data manipulation.
I am having trouble doing this because swift is viewing the array as a single object.
ex. dict[1]!.count will print 1 not 7 (ie. the 7 values)
Is there a way to do this - meaning to get swift to store the value as an array of Doubles?
Thanks.
It would be nice if you shared some code with us. but to access a dictionary of arrays you can do something like this :
let array1 = ["a", "b" , "c"]
let array2 : [Float] = [1.2,2.8,3.4]
let dictionary : Dictionary<String, Any> = ["array1" : array1, "array2" :array2]
var arrayFromDictionary = dictionary["array1"] as! [String]
var array2FromDictionary = dictionary["array2"] as! [Float]
print(arrayFromDictionary[1])
print(array2FromDictionary[2])
the first print call will print out "b" since it is the second member of the array1.
the second print call will print out 3.4 since it is the third member of array2.
does this answer your question ?
I have swift array of tuples [(String, String)] and would like to cast this array to NSMutableArray. I have tried this and it is not working:
let myNSMUtableArray = swiftArrayOfTuples as! AnyObject as! NSMutableArray
Since swift types like Tuple or Struct have no equivalent in Objective-C they can not be cast to or referenced as AnyObject which NSArray and NSMutableArray constrain their element types to.
The next best thing if you must return an NSMutableArray from a swift Array of tuples might be returning an Array of 2 element Arrays:
let itemsTuple = [("Pheonix Down", "Potion"), ("Elixer", "Turbo Ether")]
let itemsArray = itemsTuple.map { [$0.0, $0.1] }
let mutableItems = NSMutableArray(array: itemsArray)
There are two problems with what you are trying to do:
Swift array can be cast to NSArray, but it cannot be cast to NSMutableArray without constructing a copy
Swift tuples have no Cocoa counterpart, so you cannot cast them or Swift collections containing them to Cocoa types.
Here is how you construct NSMutableArray from a Swift array of String objects:
var arr = ["a"]
arr.append("b")
let mutable = (arr as AnyObject as! NSArray).mutableCopy()
mutable.addObject("c")
print(mutable)
I'm using Array(0, {i -> ""}) currently, and I would like to know if there's a better implementation such as Array()
plus, if I'm using arrayOfNulls<String>(0) as Array<String>, the compiler will alert me that this cast can never succeed. But it's the default implementation inside Array(0, {i -> ""}). Do I miss something?
As of late (June 2015) there is the Kotlin standard library function
public fun <T> arrayOf(vararg t: T): Array<T>
So to create an empty array of Strings you can write
val emptyStringArray = arrayOf<String>()
Just for reference, there is also emptyArray. For example,
var arr = emptyArray<String>()
See
doc
Array.kt
Empty or null? That's the question!
To create an array of nulls, simply use arrayOfNulls<Type>(length).
But to generate an EMPTY array of size length, use:
val arr = Array(length) { emptyObject }
Note that you must define an emptyObject properly per each data-type (beacause you don't want nulls). E. g. for Strings, emptyObject can be "". So:
val arr = Array(3) { "" } // is equivalent for: arrayOf("","","")
Here is a live example. Note that the program runs with two sample arguments, by default.
null array
var arrayString=Array<String?>(5){null}
var nullArray= arrayOfNulls<String>(5)
As mentioned above, you can use IntArray(size) or FloatArray(size).
I found two ways to create an empty array, the second way without a lambda:
var arr = Array (0, { i -> "" })
var arr2 = array<String>()
Regarding Kotlin's null strings, this is not allowed. You have to use String? type to allow strings to be null.
Use:
#JvmField val EMPTY_STRING_ARRAY = arrayOfNulls<String>(0)
It returns an 0 size array of Strings, initialized with null values.
1. Wrong:
#JvmField val EMPTY_STRING_ARRAY = emptyArray<String>()
It returns arrayOfNulls<String>(0)
2. Wrong:
#JvmField val EMPTY_STRING_ARRAY = arrayOf<String>()
It returns an array containing the Strings.
Simplest way to initialise array and assigning values :
val myArray: Array<String> = Array(2) { "" }
myArray[0] = "Java"
myArray[1] = "Kotlin"
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)
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"]