Checking populated array in Swift4 - arrays

Keep getting error Value of type [String] has no member removeAtIndex
Does any help, please?
Thanks
var strings2 = ["a", "b", "c", "d"]
if strings2.isEmpty {
print("empty")
}
else {
print("populated") // populated
}
strings2.insert("a", at: 0) // Insert, not replace
print(strings2.removeAtIndex(0)) // a

The function is called remove(at:).
print(strings2.remove(at: 0))

Related

Divide array into subarrays

I have the following array, I have to make sure to divide it in this way into subarray, taking into consideration the first part of the name followed by / as a criterion for subdivision, for example "name/other".
Can you give me a hand?
var a = ["origin/a", "origin/b", "origin/c", "remo/a", "remo/d", "remo/c", "next/g"]
var b = {
origin: ["a", "b", "c"],
remo: ["a", "d", "c"],
next: ["g"]
}
You could used reduce(into:_:) to do so:
let reduced = a.reduce(into: [String: [String]]()) { partialResult, currentTerm in
let components = currentTerm.components(separatedBy: "/")
guard components.count == 2 else { return }
partialResult[components[0]] = partialResult[components[0], default: [String]()] + [components[1]]
}
print(reduced)
Output:
$>["remo": ["a", "d", "c"], "next": ["g"], "origin": ["a", "b", "c"]]
One idea is like this:
First we need to separate the keys for the dictionary and all the values that need to be gathered together:
let keysValues = a
.map { $0.components(separatedBy: "/") }
.compactMap { components -> (String, String)? in
guard components.count == 2 else { return nil }
return (components.first!, components.last!)
}
Now we need to reduce that into a dictionary of [String: [String]] by grouping together the values for each key:
var dict: [String: [String]] = [:]
let answer = keysValues.reduce(into: dict) { (d, kv) in
let (k, v) = kv
d[k, default: []] += [v]
}

Looping through an array in SwiftUI

I have an array of strings I want to loop through and create a view for each element. To achieve that, I tried using ForEach(), the output of the code below are the following errors:
Cannot convert value of type '[String]' to expected argument type 'Binding<C>'
Generic parameter 'C' could not be inferred
Code:
struct HomeView: View {
let array: [String] = ["A", "B", "C", "D", "E", "F", "G"]
var body: some View {
VStack {
ForEach(array, id: \.self) { letter in
Text(array[letter])
}
}
}
}
PS: The code is simplified
Desired output:
VStack of all letters from the array
You can try this (just use the letter parameter from the for loop):
let array: [String] = ["A", "B", "C", "D", "E", "F", "G"]
var body: some View {
VStack {
ForEach(array, id: \.self) { letter in
Text(letter)
}
}
}

Swift 3 - Check if a string exist inside an array and sort it

I have this special array var myArray : [Array<String>] = [["a"],["b"],["c"]]
I want to detect if "a" is already inside myArray
and after i would like to sort my array alphabetically but i havn't found any function to do all these things for my array
To find if your [[String]] contains "a", you can use contains twice:
var myArray : [Array<String>] = [["a"],["b"],["c"]]
if myArray.contains(where: { $0.contains("a") }) {
print("a found")
}
To sort the inner arrays, apply map to the outer array and sort each element:
var myArray : [Array<String>] = [["c", "a"], ["e", "b"], ["d"]]
let sorted = myArray.map { $0.sorted() }
print(sorted)
[["a", "c"], ["b", "e"], ["d"]]

Merge Arrays and Remove Duplicates Swift & Firebase

I've got an application that retrieves data from a Firebase Database. My issue is that whenever the data is updated, it retrieves a whole new array of the data (and appends it at the end of the array). For example, if my array is :
["A", "B", "C", "D", "E"]
And I attempt to remove D (in a tableView; when I swipe to delete, it removes the entry from Firebase), the array becomes
["A", "B", "C", "E", "A", "B", "C", "E"]
I have tried using the array removeAll() method before returning the array, but my tableView refreshes before it can finish; so it crashes saying index out of range. Is there anyway that I can create a second array in my database update function, and then call a merge method with my main array, and prevent adding duplicates every time? Thanks!
Code:
self.conditionRef.observeEventType(FIRDataEventType.Value, withBlock: { (snapshot) in
self.stocks.removeAll()
self.stockObjects.removeAll()
if snapshot.value is NSNull {
print("nothing found")
self.title = "No Results"
}
else {
for i in snapshot.children {
self.stocks.append(i.key)
}
print(self.stocks)
}
for stock in self.stocks {
let stockSnapshot = self.conditionRef.child(stock)
stockSnapshot.observeEventType(FIRDataEventType.Value, withBlock: { (snapshot) in
if snapshot.value is NSNull {
print("nothing found")
} else {
let price = snapshot.childSnapshotForPath("price").value as! String
let volume = snapshot.childSnapshotForPath("volume").value as! String
let stockObj = StockObject(name: stock, price: price, volume: volume)
self.stockObjects.append(stockObj)
print(stockObj.name)
print(stockObj.price)
print(stockObj.volume)
}
self.tableView.reloadData()
})
}
})
UPDATE: I have solved my issue by converting my StockObject class to equatable and adding this function to the class:
func == (lhs: StockObject, rhs: StockObject) -> Bool {
return lhs.name == rhs.name
}
Then, in the code I have above, I have replaced the line where I append to the array with this:
if self.stockObjects.contains(stockObj) == false {
self.stockObjects.append(stockObj)
}
So far, everything works as it should. Any ideas on where this might crash?

Xcode Swift check if array contains object

I have this array :
var preferiti : [ModalHomeLine!] = []
I want to check if the array contains the same object.
if the object exists {
} else {
var addPrf = ModalHomeLine(titolo: nomeLinea, link: linkNumeroLinea, immagine : immagine, numero : titoloLinea)
preferiti.append(addPrf)
}
Swift has a generic contains function:
contains([1,2,3,4],0) -> false
contains([1,2,3,4],3) -> true
So it sounds like you want an array without duplicate objects. In cases like this, a set is what you want. Surprisingly, Swift doesn't have a set, so you can either create your own or use NSSet, which would look something like this:
let myset = NSMutableSet()
myset.addObject("a") // ["a"]
myset.addObject("b") // ["a", "b"]
myset.addObject("c") // ["a", "b", "c"]
myset.addObject("a") // ["a", "b", "c"] NOTE: this doesn't do anything because "a" is already in the set.
UPDATE:
Swift 1.2 added a set type! Now you can do something like
let mySet = Set<String>()
mySet.insert("a") // ["a"]
mySet.insert("b") // ["a", "b"]
mySet.insert("c") // ["a", "b", "c"]
mySet.insert("a") // ["a", "b", "c"] NOTE: this doesn't do anything because "a" is already in the set.

Resources