This question already has answers here:
What is an optional value in Swift?
(15 answers)
Confused about Swift Array Declarations
(2 answers)
Closed 5 years ago.
According to the Apple documentation, this is the proper way to create an empty array of a specific object type in Swift 4:
var output_list = [Output]()
In the wild I have seen slightly different array declarations. I believe the following is functionally identical to the previous declaration:
var output_list: [Output] = []
However I'm fairly confident that the following two declaration methods have nuanced differences from the above:
var output_list: [Output]?
var output_list: [Output]!
What are the effective differences to the above listed methods of declaring an array as as instance variable in a Swift 4 class?
EDIT: Okay I understand that for the last two examples the variable declaration is an optional, not a generic array declaration. What about this:
var output_list: [Output?]
Is this effectively the same as var output_list = [Output]()?
Also, is var output_list = [Output]() === var output_list: [Output] = []?
Related
This question already has answers here:
how can I check if a structure is in the array of structures based on its field in Swift3?
(3 answers)
Get element from array of dictionaries according to key
(1 answer)
Closed 5 years ago.
I have a model object called user.
how to find my user.id from all users collection.
I need something like this UsersCollection.contains(user.id)
and returns Bool value.
Here you go.
let contains = UsersCollection.contains{ $0.id == 0 }
Edit:
let object = UsersCollection.first{ $0.id == 0 } // object is optional here.
This question already has answers here:
How does String.Index work in Swift
(4 answers)
Closed 6 years ago.
I just started with Swift a few days ago and I am struggling with all the different Datatypes...
Lets say we do this:
var myarray = ["justin", "steve", "peter"]
var newString = myarray[2]
so why I cant now print just the "p" from "peter"?
print(newString[0])
---> gives me an error:
"'subscript' is unavailable: cannot subscript String with an Int"
in this topic:
[Get nth character of a string in Swift programming language
it says:
"Note that you can't ever use an index (or range) created from one string to another string"
But I cant imagine, that there isn't way to handle it...
Because When I do this:
var myarray = ["justin", "steve", "p.e.t.e.r"]
var newString = myarray[2]
let a : [String] = newString.componentsSeparatedByString(".")
print(a[2])
then it works. It prints (in this case) "t".
So how I can split it "SeparatedByString" 'Nothing'?
Im sure to solve this will help me also at many other problems.
I hope I postet the question in the way it should be done.
Thank you for any solution or tips :)
The instance method componentsSeparatedByString applied to a String instance yields an array of String instances, namely [String]. The elements of an array can be indexed in the classic Java/C++ fashion (let thirdElement = array[2]).
If you'd like to split your String instance ("peter") into an array of single character String instances, you can make use of the CharacterView property of a String instance, and thereafter map each single Character in the CharacterView back to a single-character String instance
let str = "peter"
let strArray = str.characters.map(String.init(_:)) // ["p", "e", "t", "e", "r"]
let thirdElement = strArray[2] // t
This is quite roundabout way though (String -> CharacterView -> [String] -> String), and you're most likely better off simply looking at the excellent answer (covering direct String indexing) in the dupe thread dug up by #Hamish:
How does String.Index work in Swift 3
The possible corner case where the above could be applicable, as pointed out by Hamish below, is if you very frequently need access to characters in the String at specific indices, and like to make use of the O(1) random access available to arrays (more so applicable if you are working with immutable String:s, such that the corresponding String array only needs to be generated once for each immutable String instance).
I'm trying to figure out my errors in a swift program it is my first program in swift and I'm learning the syntax. How would one declare an array in swift?
If you wish to declare an array in Swift there are two ways. The most popular and most idiomatic is to use square brackets around a type. For an Array of Ints you might have:
var myArrayOfInts : [Int]
This is syntax sugar for using the generic Array struct so you could equivalently write:
var myArrayOfInts : Array<Int>
Though I don't believe I have ever seen that written in any code (after the square bracket syntax was introduced) in any case that wasn't an example (just like this one) of how the two are equivalent.
You should Try
var temp = [Int]()
Very simple
var myArray: [String] = []
This question already has an answer here:
Array.create and jagged array
(1 answer)
Closed 6 years ago.
I'm experiencing some behavior in f# that i do not understand. I was trying to create a 2d table using nested arrays. The sub-arrays will have the same length, so I could have used Array2D. However later on I will need the table rows as normal arrays, so in order to avoid conversion from a multidimensional to a regular array I want to represent the table as a jagged array.
The following code is an example of how I initialize and assign elements in the table.
let table = Array.create 3 (Array.zeroCreate<int> 2);;
table.[0].[0] <- 1;;
I would expect this piece of code to set the first element in the first row. However, what it actually does is setting the first element in all three rows.
table;;
val it : int [] [] = [|[|1; 0|]; [|1; 0|]; [|1; 0|]|]
Why does table.[0].[0] set the first element in all three sub-arrays? I tried finding the memory addresses of the sub-arrays using System.Runtime.InteropServices.Marshal.UnsafeAddrOfPinnedArrayElement, and it seems to me that they are different, so they three rows are not the same array. What is going on here?
When you use array.create, it takes as an argument an object, not a function.
As a result, each element of the jagged array is a reference to the same array, so you get the observed behaviour.
Just use a function other than array.create to make the array
This question already has answers here:
Remove matched item from array of objects?
(5 answers)
Closed 7 years ago.
So I have an array of Int's and I am trying to create a function to delete a certain value from the array. However, the removeAtIndex() function only deletes the first occurrence and the removeLast() only removes the last. I tried enumerating through the array but I end up with an Array index out of range error, possible due to the reshifting that occurs when deleting an item from the array.
for (index, value) in connectionTypeIDs.enumerate() {
if (value == connectionTypeToDelete){
connectionTypeIDs.removeAtIndex(index)
}
}
Any ideas on how to accomplish this?
The quickest way is to use filter. I don't know is that answer your question but you can have a look on this:
// remove 1 from array
arr = arr.filter{$0 != 1}