gpt4 book ai didi

arrays - 如何用另一个结构填充 结构

转载 作者:可可西里 更新时间:2023-11-01 02:23:02 24 4
gpt4 key购买 nike

我在 Xcode 中使用快速语言编程的应用程序:

我有一个像这样的结构:

struct PageFilter {
var key: Int?
var title: NSString?
}

然后我的值在:过滤器来自 API,我将它们保存到 extractedFilter

if let filters = filters {
for filter in filters {

var extractedFilter = PageFilter()
extractedFilter.key = filter["key"].integerValue
extractedFilter.title = filter["title"].stringValue

}
}

我有一组页面过滤器,例如:

lazy var availableFilters = Array<PageFilter>()

我想用 ExtractedFilter 填充 availableFilters

******* *我通过像这样的代码循环解决了这个问题:

 var strFilter : String = ""

for var i = 0; i < self.newFilterList.availableGuildFilters.count; i++ {
let guildFilter = self.newFilterList.availableGuildFilters[i]
if guildFilter.selected {
strFilter += "\(guildFilter.key),"
}
}

感谢大家*

最佳答案

下面的 Swift 1.2 playground 代码可以做到这一点——我已经放入了一个函数来模拟对 API 的调用

//: Playground - noun: a place where people can play

import Cocoa

struct PageFilter {
var key: Int?
var title: NSString?
}

// this would be replaced by whatever way you get your filters from the API
func getFiltersFromApi() -> [PageFilter]? {
// return nil // uncomment this line to demo the API returning nothing
return [PageFilter(key: 1, title: "one"),
PageFilter(key: 2, title: "two"),
PageFilter(key: 3, title: "three"),
PageFilter(key: nil, title: nil)
]
}

let filters: [PageFilter]? = getFiltersFromApi() // API call, this could return nil
let extractedFilters: [PageFilter]

if let filters = filters {
extractedFilters = filters.map { filter in
PageFilter(key: filter.key, title: filter.title)
}
} else {
extractedFilters = []
}

for filter in extractedFilters {
println("key: \(filter.key), title: \(filter.title)")
}

或者你可以像这样拥有你的惰性变量

var availableFilters: [PageFilter] = {
let filters: [PageFilter]? = getFiltersFromApi() // API call, this could return nil

if let filters = filters {
return filters.map { filter in
PageFilter(key: filter.key, title: filter.title)
}
} else {
return []
}
}()

代码类似于 Leonardo 的答案,主要区别在于使用 map 函数而不是 for ... in ...

关于arrays - 如何用另一个结构填充 <array> 结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29795675/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com