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"
Related
I have a 2d array and I want to check whether an array exists inside the 2d array.
I have tried:
var arr = Array(Array(2,1), Array(4,3))
var contain = arr.contains(Array(4, 3))
println(contain)
This should print true but it doesn't work.
Method contains doesn't work because it uses equals to determine equality and for arrays equals is using reference equality, so it will return true only for two references pointing the same object.
You could use find + sameElements:
var arr = Array(Array(2,1), Array(4,3))
var contain = arr.find(_.sameElements(Array(4, 3))).isDefined
println(contain)
Consider using ArrayBuffer instead of Array, if you need mutable collection, like so
val arr = ArrayBuffer(ArrayBuffer(2,1), ArrayBuffer(4,3))
val contain = arr.contains(ArrayBuffer(4, 3))
println(contain)
which outputs
true
Also consider question What is the difference between ArrayBuffer and Array
A more elegant solution would be the following
val array = Array(Array(2,1), Array(4,3))
val result = array.exists(_.sameElements(Array(4, 3)))
println(result)
Output
true
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 have an Array of Image links -
let alamofireSource = [AlamofireSource(urlString: Img1!)!, AlamofireSource(urlString: Img2!)!,
AlamofireSource(urlString: Img3!)!, AlamofireSource(urlString: Img4!)!]
slideshow.setImageInputs(alamofireSource)
some posts have only one image or two or three, and so on. so, sometimes image 2 (for example) is nil, In that case, I don't want it to be added to the array, is that possible?
You can try ( Swift 4 )
let arr = [img1,img2].compactMap{$0}.map{AlamofireSource(urlString:$0)!}
or
let arr = alamofireSource.compactMap{$0}
for Swift 3
let arr = alamofireSource.flatMap{$0}
so, sometimes image 2 (for example) is nil, In that case, I don't want
it to be added to the array, is that possible?
Yes it is. Although I would go with Sh_Khan's suggestion to use the compactMap method to achieve it, but it would be useless for your current case:
Based on your code snippet, I'd assume that alamofireSource of type [AlamofireSource], but not [AlamofireSource?] and that's because you are forcibly unwrap its elements (by adding ! to each of its elements). So far alamofireSource doesn't contain nils (actually it could be more danger than just a declaration, your app might crash!)
So first of all, I would recommend to remove the ! from alamofireSource:
let alamofireSource = [AlamofireSource(urlString: Img1!),
AlamofireSource(urlString: Img2!),
AlamofireSource(urlString: Img3!),
AlamofireSource(urlString: Img4!)]
which means let it be as [AlamofireSource?], therefore you would gain the benefit of using compactMap(_:):
Returns an array containing the non-nil results of calling the given
transformation with each element of this sequence.
As:
let alamofireSourceWihoutNils = alamofireSource.compactMap { $0 }
Assuming you put your Optional url strings into an array, say urlStrings (of type [String?]), you can construct alamofireSource according to (Swift 4):
let alamofireSource = urlStrings.compactMap { $0.map(AlamofireSource.init) }
Which make use of the map(_:) operator of Optional and compactMap(_:) to unwrap the two-level optionality.
Details
Your example contains two levels of optionality:
The optional ImgX arguments of type String? - henceforth referred to and named as img1, ..., img4, as CapitalFirstLetter names are reserved for e.g. types, not type instances.
The failable initilizer init?(urlString: String, placeholder: UIImage? = nil) of AlamofireSource.
First of all, lets gather the optional image links (imgX) into an array
let urlStrings = [url1, url2, url3, url4] // [String?]
Swift 4
You can combine the map(_:) operator of Optional with compactMap(_:) to safely unwrap and make use of the .some entires of urlStrings, thereafter collect the successful invocations of the failable initializer of AlamofireSource:
let alamofireSource = urlStrings.compactMap { $0.map(AlamofireSource.init) }
// or, use a named closure argument
let alamofireSource = urlStrings.compactMap { str in str.map(AlamofireSource.init) }
Swift 3
If using Swift 3, replace the compactMap(_:) invocation above with flatMap(_:):
let alamofireSource = urlStrings.flatMap { $0.map(AlamofireSource.init) }
// or, use a named closure argument
let alamofireSource = urlStrings.flatMap { str in str.map(AlamofireSource.init) }
I try to slice an 1D Array[Double] using the slice method. I've written a method which returns the start and end index as a tuple (Int,Int).
def getSliceRange(): (Int,Int) = {
val start = ...
val end = ...
return (start,end)
}
How can I use the return value of getSliceRange directly?
I tried:
myArray.slice.tupled(getSliceRange())
But this gives my a compile-Error:
Error:(162, 13) missing arguments for method slice in trait IndexedSeqOptimized;
follow this method with `_' if you want to treat it as a partially applied function
myArray.slice.tupled(getSliceRange())
I think the problem is the implicit conversion from Array to ArrayOps (which gets slice from GenTraversableLike).
val doubleArray = Array(1d, 2, 3, 4)
(doubleArray.slice(_, _)).tupled
Function.tupled[Int, Int, Array[Double]](doubleArray.slice)
(doubleArray.slice: (Int, Int) => Array[Double]).tupled
Two options here, the first one is to call your function twice:
myArray.slice(getSliceRange()._1, getSliceRange()._2)
or to save your Tuple beforehand:
val myTuple: (Int, Int) = getSliceRange()
myArray.slice(myTuple._1, myTuple._2)
Edit: I leave this here just in case but Peter Neyens posted the expected answer.
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)