I have 2 arrays of [NSURL] and they have the same elements with different order. I am trying to use the array1's indexpath to get the member, and detect member's indexPath in the other array.
I couldn't figure out if I can detect the member's index on type NSURL. I thought one way could be using for loop for the second array, however the way I could think of was..
For loop through the array2 and convert each to string to have a [string] and using another for loop to find the index of the string that I'm looking for
let array1 = [NSURL]()
let array2 = [NSURL]()
array1 = [abc, qwe, jkl]
array2 = [jkl, abc, qwe]
// To wrap up..
// For jkl, I want to use array1[2] and get array2[?]
let searchIndex = 2
if array1[2].absoluteString.isNotEmpty {
let stringToSearch = array1[2].absoluteString
}
let index = array2.indexOf { $0.absoluteString == array1[2].absoluteString }
Related
I've array with several elements, I want to generate a random element from that array and after generating I want to remove that element. I tried remove method but it returns an error Cannot find 'randSachmeli' in scope randSachmeli is a random generated array
struct SachmelebiData {
let name:String
let link:String
}
var mainMenu:[SachmelebiData] = [
SachmelebiData(name: "ხინკალი", link: ""),
SachmelebiData(name: "მწვადი", link: ""),
SachmelebiData(name: "yleyveri", link: "")
]
let yvelaSachmeli:[SachmelebiData] = mainMenu
var randSachemli = yvelaSachmeli.randomElement()
yvelaSachmeli.remove(randSachmeli)
Get random elements from the index by getting random index from array indices. And then delete the element by index.
var yvelaSachmeli:[SachmelebiData] = mainMenu
// Get the random element from the array
guard let randomIndexFromArray = yvelaSachmeli.indices.randomElement() else {
return
}
// Get the element from the index
var randSachemli = yvelaSachmeli[randomIndexFromArray]
// Remove the element by index
yvelaSachmeli.remove(at: randomIndexFromArray)
I am trying to filter my dictionary according to user input in UISearchController. I have following model and array of objects.
struct People {
var name: String
var id: Int
}
let first = People(name: "Atalay", id: 1)
let second = People(name: "Ahmet", id: 2)
let third = People(name: "Mehmet", id: 3)
let fourth = People(name: "Yusuf", id: 4)
let peoples: [People] = [first, second, third, fourth, fifth]
I put them into a dictionary to create section indexed table view with following code.
var dict: [String: [People]] = Dictionary(grouping: peoples, by: { (people) -> String in
return String(people.name.prefix(1))
})
Above code gives me a dictionary with first letter of People names. Now, I would like to filter my array according to user input. However, I tried following code for filtering but it is not working as I expected.
let filteredDict = (dict.filter { $0.1.contains { $0.name.lowercased().contains("ata") } })
It returns all "A" letter section indexes like ["A": People(name: "Atalay", id: 1), People(name: "Ahmet", id: 2)]
How can I achieve filter also my array inside dictionary?
If I'm not mistaken, you want your final dictionary to have all the keys and only the filtered array of items as the values. If that is right, reduce is the tool for that:
let filtered = dict.reduce(into: [String: [People]]()) {
$0[$1.key] = $1.value.filter { $0.name.lowercased().contains("ata") }
}
I decided it was simplest to get this right by using an old fashioned for loop and filter each group separately
var filtered = [String: [People]]()
for (k, v) in dict {
let result = v.filter {$0.name.lowercased().contains("ata")}
if result.count > 0 {
filtered[k] = result
}
}
Note that if you want to keep all the groups in the result dictionary just skip the if result.count > 0 condition
How can I achieve filter also my array inside dictionary?
You should have an array first, you can use flatMap to group all the values in your filteredDict
let array = filteredDict.flatMap { $0.value }
Then you just filter the array as usually
let filteredArray = array.filter { $0.name.lowercased().contains("ata") }
I have an array myarray and I am using a for loop to get a few information which I add to myarray. But next time the for-loop runs, I don't want to create a separate index, but instead the 2nd time and so on, I want to append the information to myarray[0].
How do I do that?
var myarray = [String]()
for var j in 0 < 12 {
// do some stuff
for var i in 0 ..< 10 {
let parta = json?["users"][j]["name"].string
let partb = json?["users"][j]["Lname"].string
let partc = json?["users"][j]["dob"].string
myarray.append("\(parta)-\(partb)-\(partc)---")
// Here when the for loop comes back again (i = 1) , i dont want to make
// myarray[1] , but instead i want myarray[0] ,
// having value like [parta-partb-partc--parta-partb-partc]
}
}
Basically what I am trying to do is, append the new name/lname/dob values at myarray[0] without affecting the current value/string at myarray[0].
You can insert single element and also add array as below.
Swift 5
var myarray = [String]()
myarray.insert("NewElement", at: 0)
myarray.insert(contentsOf: ["First", "Second", "Third"], at: 0)
If I understand your question correctly, you want to create one long string and add the new data always at the beginning of the string. One way to do that would be:
// Store somewhere
var myString = String()
for var i in(0..<10) {
let parta = json?["name"].string
let partb = json?["Lname"].string
let partc = json?["dob"].string
let newString = "\(parta)-\(partb)-\(partc)---")
newString.append(myString)
myString = newString
// Here when the for loop comes back again (i = 1) , i dont want to make
//myarray[1] , but instead i want myarray[0] ,
//having value like [parta-partb-partc--parta-partb-partc]
}
Hi I would like to store values of a 1D array into a 2D array.
My 1D array has 50 elements and I want to store it in a 5x10 array, but whenever I do that, it always gives me a "Index out of range" error
Any help would be appreciated thanks!
var info2d = [[String]]()
var dataArray = outputdata.components(separatedBy: ";")
for j in 0...10 {
for i in 0...5 {
info2d[i][j] = dataArray[(j)*5+i]
print(info2d[i][j])
}
}
Lots of error in your code.
info2d must be initialised with default values before using it by index
// initialising 2d array with empty string value
var info2d = [[String]](repeating: [String](repeating: "", count: 10), count: 5)
Secondly for loop with ... includes the last value too, use ..<
for j in 0..<10 {
//...
}
Thirdly (j)*5+i is incorrect too.
Better Read how to use arrays, collections and for loop in swift.
https://docs.swift.org/swift-book/LanguageGuide/ControlFlow.html
https://docs.swift.org/swift-book/LanguageGuide/CollectionTypes.html
I would make use of ArraySlice for this.
var arr2D = [[String]]()
for i in 0..<5 {
let start = i * 10
let end = start + 10
let slice = dataArray[start..<end] //Create an ArraySlice
arr2D.append(Array(slice)) //Create new Array from ArraySlice
}
I have 2 Array of type [Any] - objects of dictionaries
And other array contains other set of objects [Any] (2nd array objects are contains in first array)
I need to find the index of the first array of second array elements
eg: -
let firstArray = [["key1":6],["key2":8],["key3":64],["key4":68],["key5":26],["key6":76]]
let secondArray = [["key3":64],["key6":68]]
How can I find the firstArray index of secondArray elements
let index = firstArray.index{$0 == secondArray[0]};
print("this value ", index);
will print optional(2) , it is basically 2
First, you take the keys from your secondArray. Then, you try to find the index of key in your firstArray. Be aware that some values might be nil if the key doesn't exist.
let firstArray = [["key1":6],["key2":8],["key3":64],["key4":68],["key5":26],["key6":76]]
let secondArray = [["key3":64],["key6":68], ["key8": 100]]
let indexes = secondArray
.map({ $0.first?.key }) //map the values to the keys
.map({ secondKey -> Int? in
return firstArray.index(where:
{ $0.first?.key == secondKey } //compare the key from your secondArray to the ones in firstArray
)
})
print(indexes) //[Optional(2), Optional(5), nil]
I also added an example case where the result is nil.