我是iOS开发的新手,对于我目前的应用,我需要执行以下操作:
所以,这就是我所拥有的:
@IBOutlet weak var start_btn: UIButton!
fileprivate var searches = [FlickrSearchResults]()
fileprivate let flickr = Flickr()
override func viewDidLoad() {
super.viewDidLoad()
flickr.searchFlickrForTerm("cat") {
results, error in
if let results = results {
print("Found \(results.searchResults.count) matching \(results.searchTerm)")
self.searches.insert(results, at: 0)
因此,我想要将结果(有500条记录)分成10个批次,而不是最后一行,以便以后我可以从搜索数组中逐批地获取它们。
你能告诉我这是不是一个好主意以及如何实现它?
答案 0 :(得分:2)
我认为这不是个好主意。要稍后拆分数组,您可以使用两个变量 - startIndex
和endIndex
。例如,如果您只想显示0到9个索引的记录,请编写如下内容:
startIndex = 0
endIndex = 9
let resultsBatch = results[startIndex...endIndex]
答案 1 :(得分:2)
这是一个简单的Swift 4扩展Array
以扩展数组。
extension Array {
func chunked(by size: Int) -> [[Element]] {
return stride(from: 0, to: count, by: size).map { index in
Array(self[index..<Swift.min(index + size, count)])
}
}
}
在您的代码中,您需要存储所有结果,然后只显示您感兴趣的页面。
@IBOutlet weak var start_btn: UIButton!
fileprivate var chunkedResults = [[FlickrPhoto]]()
fileprivate var searches = [FlickrPhoto]()
fileprivate let flickr = Flickr()
override func viewDidLoad() {
super.viewDidLoad()
flickr.searchFlickrForTerm("cat") { results, error in
if let results = results {
print("Found \(results.searchResults.count) matching \(results.searchTerm)")
self.chunkedResults = results.searchResults.chunked(size: 10)
self.searches = self.chunkedResults.first ?? []
答案 2 :(得分:0)
您可以在创建具有内部数组列表的数组中执行此操作。请在下面找到示例代码:
@IBOutlet weak var start_btn: UIButton!
// Make a array list which can store arrays of FlickrSearchResults
fileprivate var searches = [[FlickrSearchResults]]()
fileprivate let flickr = Flickr()
override func viewDidLoad() {
super.viewDidLoad()
flickr.searchFlickrForTerm("cat") {
results, error in
// Prepare some section / counter / insideArray varaibles to split your values
var section = 0
var counter = 0
var insideArray = [FlickrSearchResults]()
if let result = results {
if counter < 9 {
// Fill the inside array list, if we reach 10 values, they will be stored in your searches array list
insideArray.append(result)
if result == results.last {
// If you identify the end of your values
searches.insert(insideArray, at: section)
continue
}
counter = counter + 1
} else {
// Store the first 10 values in your array list section [0], then the next 10 values in section[1], etc.
insideArray.append(ar)
searches.insert(insideArray, at: section)
counter = 0
section = section + 1
insideArray = []
}
}
}
}
答案 3 :(得分:0)
也许它会有用:
let resultsCount = 505
let batchSize = 10
var startIndex = 0
var endIndex = 0
let batchesCount = Int(results.count / batchSize)
let batchRest = results.count % batchSize
var batches: [[Int]] = []
for batch in 0..<batchesCount {
startIndex = batch * batchSize
endIndex = startIndex + batchSize
batches.append(Array(results[startIndex...endIndex]))
}
let lastBatch = Array(results[endIndex..<endIndex + batchRest])
batches.append(lastBatch)
print(batches)