Here's what I would like to do.
number = [ 0, 1, 2]
array0 = [ "AA", "BB"]
array1 = [ "CC", "DD"]
array2 = [ "EE", "FF"]
I want to be able to be able to reference the name of the array by doing something like this.
selectedArray = "array" + String(number[2])
then with this, I would like to be able to reference the values inside such as
print("array2:\(selectedArray[1]))
/// The answer would be --> array2:FF
Right now, I've not been able to achieve this, and I tried this but it doesn't work.
selectedArray = Array("array" + String(number[2]))
I tried googling but not knowing how to describe this, I didn't fare well in the results.
Note : The array is a list of GPS Dist / Lat / Lon (very long) and rather than have 1 very huge array, I'm thinking of splitting them out into eg: 10 diff arrays
Not sure I understand correctly what you are trying to achieve and the logic but you can create an array of arrays (lat and long). Something like this:
let number = [0,1,2] // not sure why you need this array
let array = [[ "AA", "BB"],
[ "CC", "DD"],
[ "EE", "FF"]]
let selectedNumber = number[2]
print("array\(selectedNumber):\(array[selectedNumber][1])")
However, I would advice to use this approach:
create a Model for you Coordinates
struct Coordinates {
var lat:String //this should be a Double but
//for the sake of the example I use String
var long:String //Same here
}
then in the controller add data to an array of Coordinates
let coordinate1 = Coordinates(lat: "AA", long: "BB")
let coordinate2 = Coordinates(lat: "CC", long: "DD")
let coordinate3 = Coordinates(lat: "EE", long: "FF")
let array2:[Coordinates] = [coordinate1,coordinate2,coordinate3]
let selectedNumber = number[2]
print("array\(selectedNumber):\(array2[selectedNumber].long)")
which still prints
array2:FF
Related
I have an array of 3 dictionaries which looks something like this:
array1 = [["measure1":"90", "measure2":"200","measure3":"23", "measure4":"190"],["measure1":"60", "measure2":"340","measure3":"531", "measure4":"2000"],["measure1":"210", "measure2":"2","measure3":"12", "measure4":"743"]]
Then I also have an array like this:
array2 = ["10","20","30"]
I am trying to replace all the values of "measure4" in the array of dictionaries with the values in array2, in order (i.e. the first "measure4" becomes "10", the second "20" etc)
It feels like the answer should be simple, but i've been trying various different for in loops and nothing brings out the correct array of dictionaries, which should look like this:
array1 = [["measure1":"90", "measure2":"200","measure3":"23", "measure4":"10"],["measure1":"60", "measure2":"340","measure3":"531", "measure4":"20"],["measure1":"210", "measure2":"2","measure3":"12", "measure4":"30"]]
Any help is much appreciated.
for (i, x) in array2.enumerated() {
array1[i]["measure4"] = x
}
array1[0]["measure4"]? = array2[0]
array1[1]["measure4"]? = array2[1]
array1[2]["measure4"]? = array2[2]
or as a loop
for i in 0..<min(array1.count, array2.count) {
array1[i]["measure4"]? = array2[i]
}
Try this code:
let new = array1.enumerated().reduce([[String: String]](), { acc, elemEnumerated in
var mutableDict = elemEnumerated.element
mutableDict["measure4"] = array2[elemEnumerated.offset]
return acc + [mutableDict]
})
If I have the following array and I want to create a string array containing the door prizes by mapping the mysteryDoors array as keys for the dictionary, and get the corresponding values into a new array.
Thus I would get a string array of ["Gift Card", "Car", "Vacation"] how can I do that?
let mysteryDoors = [3,1,2]
let doorPrizes = [
1:"Car", 2: "Vacation", 3: "Gift card"]
You can map() each array element to the corresponding value in
the dictionary. If it is guaranteed that all array elements are
present as keys in the dictionary then you can do:
let mysteryDoors = [3, 1, 2]
let doorPrizes = [ 1:"Car", 2: "Vacation", 3: "Gift card"]
let prizes = mysteryDoors.map { doorPrizes[$0]! }
print(prizes) // ["Gift card", "Car", "Vacation"]
To avoid a runtime crash if a key is not present, use
let prizes = mysteryDoors.flatMap { doorPrizes[$0] }
to ignore unknown keys, or
let prizes = mysteryDoors.map { doorPrizes[$0] ?? "" }
to map unknown keys to a default string.
If you have to use map, then it would look something like the following:
let array = mysteryDoors.map { doorPrizes[$0] }
After re-reading the Apple Doc example code and changing it to what I need. I believe this is it (Almost). Unfortunately it is now in string format with new lines...
let myPrizes = doorPrizes.map { (number) -> String in
var output = ""
output = mysteryDoors[number]!
return output;
}
I want to implement a multiple click in my Shinobi DataGrid. I have a grid which have array
( ["1", "32", and more] )
If I click the grid I put it into new Array self.arrayNr.append(currNr).
But I want to check and remove if currNr is already exist in arrayNr it is will be remove from the arrayNr.
I'm new and using Swift 3. I read some question regarding with my question like this and this but it's not working. I think the Swift 2 is simpler than Swift 3 in handling for String. Any sugesstion or answer will help for me?
You can use index(of to check if the currNrexists in your array. (The class must conform to the Equatable protocol)
var arrayNr = ["1", "32", "100"]
let currNr = "32"
// Check to remove the existing element
if let index = arrayNr.index(of: currNr) {
arrayNr.remove(at: index)
}
arrayNr.append(currNr)
Say you have an array of string, namely type [String]. Now you want to remove a string if it exists. So you simply need to filter the array by this one line of code
stringArray= stringArray.filter(){$0 != "theValueThatYouDontWant"}
For example, you have array like this and you want to remove "1"
let array = ["1", "32"]
Simply call
array = array.filter(){$0 != "1"}
Long Solution
sampleArray iterates over itself and removes the value you are looking for if it exists before exiting the loop.
var sampleArray = ["Hello", "World", "1", "Again", "5"]
let valueToCheck = "World"
for (index, value) in sampleArray.enumerated() {
if value == valueToCheck && sampleArray.contains(valueToCheck) {
sampleArray.remove(at: index)
break
}
}
print(sampleArray) // Returns ["Hello", "1", "Again", "5"]
Short Solution
sampleArray returns an array of all values that are not equal to the value you are checking.
var sampleArray = ["Hello", "World", "1", "Again", "5"]
let valueToCheck = "World"
sampleArray = sampleArray.filter { $0 != valueToCheck }
print(sampleArray) // Returns ["Hello", "1", "Again", "5"]
I have spent some time trying to search for this and I haven't found a solution. I am trying to access a specific array value in a dictionary. Below is the general code/explanation for what I want to do.
var dict = ["1": [1,2,3,4,5], "2": [6,7,8,9,10], "3": [11,12,13,14,15]]
//now lets say I want to access the 3rd value of dict["2"] = 8
//I have tried the following and failed
print(dict["2": [2]])
print(dict["2"][2])
Thanks
Here is the way you can achieve that:
var dict = ["1": [1,2,3,4,5], "2": [6,7,8,9,10], "3": [11,12,13,14,15]]
let temp = dict["2"]![2] // 8
An NSSet can be converted to Array using set.allObjects() but there is no such method in the new Set (introduced with Swift 1.2). It can still be done by converting Swift Set to NSSet and use the allObjects() method but that is not optimal.
You can create an array with all elements from a given Swift
Set simply with
let array = Array(someSet)
This works because Set conforms to the SequenceType protocol
and an Array can be initialized with a sequence. Example:
let mySet = Set(["a", "b", "a"]) // Set<String>
let myArray = Array(mySet) // Array<String>
print(myArray) // [b, a]
In the simplest case, with Swift 3, you can use Array's init(_:) initializer to get an Array from a Set. init(_:) has the following declaration:
init<S>(_ s: S) where S : Sequence, Element == S.Iterator.Element
Creates an array containing the elements of a sequence.
Usage:
let stringSet = Set(arrayLiteral: "car", "boat", "car", "bike", "toy")
let stringArray = Array(stringSet)
print(stringArray)
// may print ["toy", "car", "bike", "boat"]
However, if you also want to perform some operations on each element of your Set while transforming it into an Array, you can use map, flatMap, sort, filter and other functional methods provided by Collection protocol:
let stringSet = Set(["car", "boat", "bike", "toy"])
let stringArray = stringSet.sorted()
print(stringArray)
// will print ["bike", "boat", "car", "toy"]
let stringSet = Set(arrayLiteral: "car", "boat", "car", "bike", "toy")
let stringArray = stringSet.filter { $0.characters.first != "b" }
print(stringArray)
// may print ["car", "toy"]
let intSet = Set([1, 3, 5, 2])
let stringArray = intSet.flatMap { String($0) }
print(stringArray)
// may print ["5", "2", "3", "1"]
let intSet = Set([1, 3, 5, 2])
// alternative to `let intArray = Array(intSet)`
let intArray = intSet.map { $0 }
print(intArray)
// may print [5, 2, 3, 1]
I created a simple extension that gives you an unsorted Array as a property of Set in Swift 4.0.
extension Set {
var array: [Element] {
return Array(self)
}
}
If you want a sorted array, you can either add an additional computed property, or modify the existing one to suit your needs.
To use this, just call
let array = set.array
ADDITION :
Swift has no DEFINED ORDER for Set and Dictionary.For that reason you should use sorted() method to prevent from getting unexpected results such as your array can be like ["a","b"] or ["b","a"] and you do not want this.
TO FIX THIS:
FOR SETS
var example:Set = ["a","b","c"]
let makeExampleArray = [example.sorted()]
makeExampleArray
Result: ["a","b","c"]
Without sorted()
It can be:
["a","b","c"] or ["b","c","a",] or ["c","a","b"] or ["a","c","b"] or ["b","a","c"] or ["c","b","a"]
simple math : 3! = 6
The current answer for Swift 2.x and higher (from the Swift Programming Language guide on Collection Types) seems to be to either iterate over the Set entries like so:
for item in myItemSet {
...
}
Or, to use the "sorted" method:
let itemsArray = myItemSet.sorted()
It seems the Swift designers did not like allObjects as an access mechanism because Sets aren't really ordered, so they wanted to make sure you didn't get out an array without an explicit ordering applied.
If you don't want the overhead of sorting and don't care about the order, I usually use the map or flatMap methods which should be a bit quicker to extract an array:
let itemsArray = myItemSet.map { $0 }
Which will build an array of the type the Set holds, if you need it to be an array of a specific type (say, entitles from a set of managed object relations that are not declared as a typed set) you can do something like:
var itemsArray : [MyObjectType] = []
if let typedSet = myItemSet as? Set<MyObjectType> {
itemsArray = typedSet.map { $0 }
}
call this method and pass your set
func getArrayFromSet(set:NSSet)-> NSArray {
return set.map ({ String($0) })
}
Like This :
var letters:Set = Set<String>(arrayLiteral: "test","test") // your set
print(self.getArrayFromSet(letters))