Difference between these arrays as member variable of view controller - arrays

I would like to have an array as a member of my table view controller. The array will be a data source.
What are the differences or advantages/disadvantages the following ways of having a member variable array.
class BinViewController: UITableViewController, WKNavigationDelegate {
var peopleArray1 = [String]()
var peopleArray2: [String] = []
var peopleArray3: [String]!
var peopleArray4: [String]?

I think there is not the right question that you need to ask yourself. There is no advantage or disadvantage. There are ways to initialize a member of a class based on what you need and your logic that you want to implement.
var peopleArray1 = [String]() you are saying to the compiler please let me create an empty array of string. It's declared and initialized. Also you let the compiler to infer the type of your array compared to your second statement.
var peopleArray2: [String] = [] it's 99% the same thing as your first statement. You are creating en empty array of String. Declared and initialized. Here the only difference is that you specify the type of your array. You don't let the compiler to infer the type of your array. var variable:TypeVariable = .... It's recommended by Apple to let the compiler to infer the type of your variables members when you can because you win a readable code
var peopleArray3: [String]! it's pretty different than your previous 2 initializations. First, you need to know that Swift is a very strongly typed language and you need to initialize every variable before using it. One thing that you can experiment is try to make the same statement without the ! or ? and you will your compiler warned you with an issue. Sometimes you just don't know what is the initial value but you are sur that at one moment, you will have a value. A variable is these two possible states : no value or a value are called Optionals. With this statement you are saying i want to create an array of string that might be nil or might have some String values. If you print your array you will have a message like "Optional([String])". To get the value of your Optional you need to unwrap it with the exclamation mark only when you are sure that you have a value. If not, your program is going to crash. Here with this initialization, you are saying to the compiler to not be worried because you know that in the future your array is going to have some values.
var peopleArray4: [String]? is the same as the previous one. The main difference is that everytime you want to access peopleArray values you will need to put an exclamation mark to unwrap his value.
There is no advantage/disadvantage just logic to use Optionals. If your array might be nil and further have values or is it a static array...

These two basically do the same thing:
var peopleArray1 = [String]()
var peopleArray2: [String] = []
They declare and initialize an empty array of type [String].
These two in the other hand, are also similar:
var peopleArray3: [String]!
var peopleArray4: [String]?
The array itself for both of them could be nil, which they currently are as they are declared.
The difference is that peopleArray3 is an implicitly unwrapped optional array of Strings, while peopleArray4 is an optional array of Strings.
What this means for peopleArray3 is that you're telling the complier that you will set a value to it before it's used. If you try to access it while its value is nil, the app will crash.
For peopleArray4, you're telling the compiler that the array might be nil at any time, so you'll need to check if peopleArray4 is not nil before you access it.

Related

In Swift, What is the difference between var myArray: [myClass] and var myArray = [Array]() [duplicate]

Is there any difference between the following?
var array1_OfStrings = [String]()
var array2_OfStrings: [String] = []
var array3_OfStrings: [String]
Testing in Playground shows that 1 and 2 are the same but 3 behaves differently.
Can someone explain me the difference please? And also what will be the preferred way to declare an empty array of String?
First two have the same effect.
declare a variable array1_OfStrings, let it choose the type itself. When it sees [String](), it smartly knows that's type array of string.
You set the variable array2_OfStrings as type array of string, then you say it's empty by []
This is different because you just tell you want array3_OfStrings to be type array of string, but not given it an initial value.
I think the first one is recommended as The Swift Programming Language uses it more often.
While I might be late to the party, there is one thing that needs to be said.
First option set array1_OfStrings to array of Strings
The other option tells that array1_OfStrings is array of Strings and then set it empty.
While this might be a really small difference, you will notice it while compiling. For the first option compiler will automatically try to find out what is the type of array1_OfStrings. Second option won't do that, you will let compiler know that this actually is array of Strings and done deal.
Why is this important? Take a look at the following link:
https://thatthinginswift.com/debug-long-compile-times-swift/
As you can see, if you don't declare type of your variable that might impact build performance A LOT.

Swift: Why do I need empty parenthesis when creating a blank array?

Why do I need parenthesis "()" after defining a blank array? For example:
let emptyArray = [String]()
But when you use an array with pre-defined values, it doesn't need them?
let populatedArray = ["Hello", "question"]
You are calling the initializer, this is similar to:
let object = MyObject()
or
let string = String()
It can be also written as
let array = Array<String>()
When you use the predefined values, the type is inferred from the type of the array items. With an empty array there are no items so the type has to be specified explicitly.
Another way to do it is:
let array: [String] = []
or
let array = [] as [String]
The simple answer (as to why it cannot be done that way) is that the compiler needs to be able to distinguish between [String] as a type and [String] as a value. When you add () it knows its a value. Remember that you can define a variable type without instantiating it using var x: [String].
Delving into it as a more complicated system, remember that both of these examples are replacements for Array<String> and Array<String>(). The need for the () here is because that's how object instantiation works. It's logical it would work the same using the shorthand [String] notation.
Addressing your last example, this certainly could be argued both ways. However it's not ambiguous (there's no doubt it refers to a value) and there's precedent for doing it that way in other languages.

How to assign an array of int to a corresponding property of an array of objects in Swift?

I'd like to assign an array of integer values to a corresponding property of an array of objects.
class MyClass {
var propint: Int = 0
var propdbl: Double = 0.0
var propstr: String = ""
} // MyClass
var arrint: [Int]()
var arrobj: [MyClass]()
One approach would be looping through the array of integers (arrint), and assign the value to the property propint of the corresponding object array element.
I'm wondering if there's a more efficient, elegant solution to this undertaking, eg. like array.map, and if so how this would be looking like.
--Sil68
I'm not sure about efficient. As #Ryan said all the built in functional methods just use a loop to process the array.
Having said that, you could do something like this...
let updatedObjectArray = zip(arrint, arrobj).map {
number, object -> MyClass in
object.propint = number
return object
}
You must be careful here though. By using a class (and not a struct) you will inadvertently be editing the original array.
Anyway, this will zip up both arrays, iterate them and then map them onto an array with the updated objects.
As a side note: choose better names for your variables. Even in Stack Overflow questions. Using variable names like arrint or arrobj or propint only do two things. Make it hard to reply to questions because auto correct wants to change them all. And make it hard to understand when reading. I know it's a property and an int (thats what the code says). The name should tell me WHY it's a property and an int.

Confused about Swift Array Declarations

Is there any difference between the following?
var array1_OfStrings = [String]()
var array2_OfStrings: [String] = []
var array3_OfStrings: [String]
Testing in Playground shows that 1 and 2 are the same but 3 behaves differently.
Can someone explain me the difference please? And also what will be the preferred way to declare an empty array of String?
First two have the same effect.
declare a variable array1_OfStrings, let it choose the type itself. When it sees [String](), it smartly knows that's type array of string.
You set the variable array2_OfStrings as type array of string, then you say it's empty by []
This is different because you just tell you want array3_OfStrings to be type array of string, but not given it an initial value.
I think the first one is recommended as The Swift Programming Language uses it more often.
While I might be late to the party, there is one thing that needs to be said.
First option set array1_OfStrings to array of Strings
The other option tells that array1_OfStrings is array of Strings and then set it empty.
While this might be a really small difference, you will notice it while compiling. For the first option compiler will automatically try to find out what is the type of array1_OfStrings. Second option won't do that, you will let compiler know that this actually is array of Strings and done deal.
Why is this important? Take a look at the following link:
https://thatthinginswift.com/debug-long-compile-times-swift/
As you can see, if you don't declare type of your variable that might impact build performance A LOT.

Handling sparse arrays in swift

I'm trying to create a sparse array in Swift. I'm not sure if the problem is in my declaration (no syntax errors detected) or possibly a bug in beta 2?
I am trying to declare an array of 24 class instances as optionals. I then can fill in slots of the array as necessary. Here is the declaration:
var usage = WaterUsage?[](count:24, repeatedValue:nil)
This gets through the Xcode 6 beta 2 compiler without error. The intention is to end up with an array of 24 "WaterUsage" classes all set to nil.
When I try to set an array element:
usage[hour] = usage
where hour is < 24 I get the error:
"WaterUsage doesn't have a member named subscript"
I've also tried using generics but that doesn't appear to work either.
I find the Swift syntax for using optionals in complex data structures is a little obscure and could use some advice here.
That way of defining the array is giving you an Optional array of Optional values ( WaterUsage?[]? ), which you have to unwrap before you can use. I think you want just the values to be optional: WaterUsage?[]. One way I've been able to do that is by using the generic Array syntax:
var usage: WaterUsage?[] = Array<WaterUsage?>(count:24, repeatedValue:nil)
usage[hour] = something
Another way is to force unwrapping of the return value of your initial declaration. I don't know why, but WaterUsage?[]() has an Optional return value.
var usage = (WaterUsage?[](count:24, repeatedValue:nil))!
usage[hour] = something
You're pretty close! When using the MemberType[] syntactic sugar for arrays, the way that you wrote it (WaterUsage?[]) actually declares the Array as Optional, as well as the values that it holds. In which case, to assign a value to an index you would need to unwrap the Array first by using:
usage![hour] = someWaterUsage
However, if you only want Optional members in the Array (and don't want the Array itself to be optional), then you can fall back to the standard Array declaration:
var usage = Array<WaterUsage?>(count:24, repeatedValue:nil)
edit:
I originally offered an alternate syntax as another solution as well:
var usage = (WaterUsage?)[](count:24, repeatedValue:nil)
...but in doing so, per #Nate's observations it then becomes the case that you need to use unwrapping twice to access the value at a specific index, for example:
usage[0]!!.someProperty
this is just a shot in the dark, but I think what may be happening in this case is not dissimilar at all to what OP originally tried with declaring the Array using WaterUsage?[]
that is, when using (WaterUsage?)[], perhaps it is seeing this declaration as an Array of Optional Tuples holding Optional WaterUsages, requiring us then to unwrap the member at the index twice before we can access its properties
interesting stuff!

Resources