I want to create an empty array that will contain strings.
What are differences between the following two approaches and which one is better to use?
var arr:[String] = []
// versus
var arr = [String]()
AFAIU, the first approach is essentially equivalent to Array<String>(arrayLiteral: ...) with empty set of literals. The second one is just Array<String>(). Despite same end result, the latter should be more preferable just because it takes less to execute. You can explore this for yourself by debugging both options with stepping into instructions.
The first one, var arr:[String] = [] is usually used for adding values upon initialisation. You could create an empty array like this, but usually you would do the second one to create the empty array: var are = [String]().
Either one is acceptable, but usually you would use the first for adding values on initialisation, just like you would with normal variables: you would normally write something like this:
var exampleVariable:String = "Example String"
and to compare the second, it would be like writing:
var exampleVariable = String()
Simply, you are adding the square brackets to show you are making an array.
I'm answering very late this question because it's missing, in my opinion they key words Type Annotation & Type Inference.
var arr: [String] = []
You are declaring a variable arr of type [String] (array of String), with the : [String] part. It's the Type Annotation
Then you assign its value with [], ie create an empty array, and since the compiler knows it's an array of String, it will create an empty array of string.
var arr = [String]()
You are creating a variable arr without specifying its type. Then, you intialize that variable, with an array of String ([String](), which is short for [String].init()).
Then, the compiler knows what's the type of arr with its initialization.
That's the Type Inference.
But if you write:
var arr = []
Compiler won't know what's arr, you need to tell it when declaring the variable with myVar: ItsType, or upon the initialization, if with = [String]().
So you'll get compiler error: Empty collection literal requires an explicit type.
Usually, using both is overkill, too verbose.
You could then also write:
// Using Type Annotation:
// Declaring the variable type, the initialization doesn't need to specify it
var arr: [String] = []
var arr: Array<String> = []
// Using Type inference:
// Initialization is expliciting the type, the type is then "guessed".
var arr = [String]()
var arr = [String].init()
var arr = Array<String>()
var arr = Array<String>.init()
// Using Type Annotation & Type Inference:
// Declaring the variable type, AND also the on the initialization
var arr: [String] = [String]()
var arr: [String] = [String].init()
var arr: Array<String> = [String]()
var arr: Array<String> = [String].init()
In my case, I prefer var arr: [String] = []. But that's my opinion.
Related
I have a variable on my class:
var list = []
and I use it on a function of my class:
func chargeData (data: NSArray){
list = data
}
It worked well on my project in Swift 2.3 but when I have updated it to XCode8 and Swift3 it gives to me the following error:
Empty collection literal requires an explicit type
so I have added a typecast to my list variable:
var list = [] as! NSArray
but it gives to me the following alert:
Forced cast of 'NSArray' to same type has no effect
I know that an alert does not broke the application but I would like to solve this error in a proper way.
Did someone got the same error and solved it properly?
Thanks in advance!
This error occurs since implicit conversions are abolished so you have to tell the compiler the explicit type (of the ArrayLiteral []):
var list: NSArray = []
// or
var list = [] as NSArray
The Swift 5 guided tour is pretty explicit about creating empty arrays or dictionaries: https://docs.swift.org/swift-book/GuidedTour/GuidedTour.html#ID461 towards the end of the first section.
To create an empty array or dictionary, use the initializer syntax.
let emptyArray = [String]()
let emptyDictionary = [String: Float]()
Update swift 4 :
var array = [] as [String]
You are mixing ObjectiveC (NSArray) and Swift (Array<T>). Items inside an NSArray are assumed to be NSObject and its subclasses, while Swift has no clue what T is since the array is empty and hence type inference doesn't work.
If you declare it like this:
var data: NSArray = []
there will be a conflict since var means mutable in Swift, but NSArray is immutable in ObjC. You can get around that by changing it to NSMutableArray, which is a subclass of NSArray:
let data = NSMutableArray() // note that we don't need var here
// as NSMutableArray is already mutable
If you want to keep data as Swift's Array, give it a type:
var data = [MyDataModel]()
// or
var data = [AnyObject]()
// usage:
chargeData(data: data as NSArray)
I am trying to pass an array to a function:
var array:[String] = []
// fill the array
array.append(uniqueId as String)
// pass the array to a function:
GamePrefrences.setLevelsArray(array)
My function is declares like this:
func setLevelsArray(arr:[String])
{
GamePrefrences.levels_array = arr
}
But on the line i try to call the function it gives with an error:
cannot invoke ... with argument list of type [(String)]
What is the problem? if its possible to provide brief explanation
First of all, your function is not a class level function and you are calling the method directly using class name.
Try like this.
var array:[String] = []
// fill the array
array.append(uniqueId as! String)
// pass the array to a function:
GamePrefrences.setLevelsArray(array)
Function declaration.
class func setLevelsArray(arr:[String])
{
GamePrefrences.levels_array = arr
}
or,
var array:[String] = []
// fill the array
array.append(uniqueId as String)
// pass the array to a function:
let instance = GamePrefrences()//Depends on you, how you defined the initialiser.
instance.setLevelsArray(array)
Your function body.
func setLevelsArray(arr:[String])
{
instance.levels_array = arr
}
please try something like this
func setLevelsArray(arr:[String])
{
let tempArr = arr
GamePrefrences.levels_array = tempArr
}
in Swift Arrays and Dictionary are passed by value not by reference, therefore if you are not changing the values or assigning to any other variable then Swift compiler does not get the copy, instead the variable still lives in the heap. so before assigning i believe it is necessary to copy this into another variable.
You have invalid declaration of an empty array. Here's how to declare empty array:
var array = [String]()
Im trying to add an array to a multi-dimensional array so i can add values to the existing array created.. I'm having trouble with this in swift so some help would be awesome
var array = [String]()
var NewArraywithValues = [[array],[int],[int]]
also how do i append the second and third values depending on the array String
Thanks
You can't do what you are trying to do. But you can make an array with other arrays as sub-arrays: But you can do something like that:
var stringArray = [String]()
var intArray = [Int]()
var doubleArray = [Double]()
var NewArraywithValues = [stringArray,intArray,doubleArray]
Also you could make an array-array of Objects:
var arrayArray:[[YourDataType]]
You then access the objects with:
var item = arrayArray[1][1]
An array of strings: [String]
An array of arrays of strings: [[String]]
The first element of the first array in an array of arrays of strings: arr[0][0]
I'm pretty new to Swift and need your help on a (probably) pretty basic problem.
I have a dictionairy:
var dict = ["title" : "Title", "Features" : ["feat1", "feat2", "feat3"], ...]
I can create a string from it like so:
var headline = dict["title"]! as string
but I couldn't manage to create an array. I tried in various combinations:
var features = dict["Features"]
var features = dict["Features"]! as Array
var features: Array = dict["Features"]
So please enlighten me! How do create an array? Is it possible at all?
You should specify the type for the array. Either
let features = dict["Features"] as [String]
or
let features = dict["Features"] as Array<String>
See the discussion of collection types in The Swift Language.
Your problem is that you don't have a type for the array. You describe the type of an array in swift by putting the type name in brackets. In your case, this will be [String]. Thus, your code should be var features = dict["Features"] as [String] for a mutable array, or use let for an immutable array. Hope this helps.
I'm studying Swift and got confusing with following syntax:
var treasures: [Treasure] = []
Treasure is custom class, declared as follow:
class Treasure: NSObject { }
In Objective-C square brackets mean method, but what do they mean in Swift?
Ok, this is the meaning of
var treasures: [Treasure] = []
var: you are declaring a variable
treasures: the name of your variable
[Treasure]: the type of your variable, in this case the type is Array of Treasure, the compiler will allow you to insert only object of type Treasure in your Array
[]: the actual object (Array) referenced by your variable, in this case an empty Array.
E.g. if you want the Array to hold 2 elements you can write
var treasures: [Treasure] = [Treasure(), Treasure()]
Hope this helps.
Update:
My example can also be written this way
var treasures = [Treasure(), Treasure()]
Infact thanks to the Type Inference the compiler can deduce the type of the variable treasures looking at the type of the assigned value.
[Treasure] is just a syntax sugar for Array<Treasure>.
The same way [String:Treasure] is just a syntax sugar for Dictionary<String,Treasure>.
[] is just an empty array of the type you defined. The same way [:] is an empty dictionary.
When it comes to Swift and square brackets, the rules are simple. They are used only in two situations:
1) working with Array and Dictionary types:
let vectors : [[Int]] = [[1,2,3],[4,5,6]]
let birthBook : [Int:[String]] = [1987:["John","William"], 1990: ["Mary"]]
2) for subscripting objects that support subscripting:
class RouteMapper {
private var routeMap : [String:String] = [:]
subscript(endpoint: String) -> String {
get {
if let route = routeMap[endpoint] {
return route
}
return "/"
}
set(newValue) {
routeMap[endpoint] = newValue
}
}
}
let routeMapper = RouteMapper()
routeMapper["users"] = "/v1/confirmed/users"
let url = routeMapper["admins"]
Since [ and ] are not allowed in custom operators, these are the only usages for now.