Reputation: 117
I'm using arrays within an array. something like var arrs = [[String()]]
then for in loop through-
for i in 0..<arrs.count {
if arrs[i].contains(textField.text!) {
self.arr[i].append(field.text!)
} else {
self.arr.append([textField.text!])
}
}
well, it only works first two inserts [["hi", "hi"]] then when i add another string "hi" this happens.
[["hi", "hi"], ["hi"]]
What i'm trying is, if "hi" is in the array append them within the "hi" section. if there is a new word, use a new section. so i tried "there" then this happens [["hi", "hi"], ["hi"], ["there"], ["there"], ["there"]]
i really dont know why the if statement isn't working properly. any master's help will be appreciated! Thank you!
So i tried it with @Nirav's 2nd answer and it worked perfect with Strings! then i tried it with my own small class(just a variable string) i got an error argument label missing 'where' the class looks like this the changed var arrs = [[String()]] to var arrs:[[CheckIt]] = []
As per request! updated all codes and the error im getting
class CheckIt {
var test:String!
init(test:String) {
self.test = test
}
}
var arrs:[[CheckIt]] = []
let testIt = CheckIt(test: "hi")
let testIt2 = CheckIt(test: "there")
let testIt3 = CheckIt(test: "bye")
let testIt4 = CheckIt(test: "terry")
arrs.append([testIt])
arrs.append([testIt2])
arrs.append([testIt3])
arrs.append([testIt4])
if let index = arrs.index(where: {$0.test.contains(testIt)}) {
print(index)
}
and the EXACT error message im getting - Error: Value of type '[CheckIt]' has no member 'test'
Upvotes: 0
Views: 3205
Reputation: 72460
The problem is that you need to break
the loop in if
and need to add new array only if there is no array match condition otherwise it will go further.
var found = false
for i in 0..<arrs.count {
if arrs[i].contains(textField.text!) {
arrs[i].append(textField.text!)
found = true
break
}
}
if !found {
arrs.append([textField.text!])
}
But this is not Swifty way what you need is to use index(where:)
and don't need to use for loop
.
if let index = arrs.index(where: { $0.contains(textField.text!) }) {
arrs[index].append(textField.text!)
}
else {
arrs.append([textField.text!])
}
Upvotes: 3