json - 检查 JSON 数组中是否存在值,如果不存在则检查下一个数组(Swift / SwiftUI)
问题描述
我有用户名和密码,我需要根据 JSON 文件中的数据检查这两者,如果两者都正确/存在,我会返回一个包含“项目”中数据的列表。
例如:如果我输入“user”作为用户名并输入“pass”作为密码,视图应该在列表中显示“Dog, Cat, Mouse, Parrot, Goldfish”。
如果我的语法不正确,可以修改 JSON 文件。
JSON:
[
{
"username": "user",
"password": "pass",
"type": "Animals",
"items": ["Dog",
"Cat",
"Mouse",
"Parrot",
"Goldfish"
]
},
{
"username": "helloworld",
"password": "firstprogram",
"type": "States",
"items": ["Not Running",
"Inactive",
"Active",
"Background",
"Suspended"
]
},
{
"username": "movielover",
"password": "bestmovies",
"type": "Movies",
"items": ["Kill Bill",
"Us",
"Parasite",
"Coco",
"Inception"
]
},
]
斯威夫特用户界面代码:
import SwiftUI
struct LoginView: View {
var userName = "user"
var items: UserModel = UserModelData().userInformation[0]//this only displays data
for the first item in the array, I would like to check each item,find the one
that contains userName, and use that index.
var body: some View{
VStack{
Text("\(items.username)'s \(items.type)")
.font(.title)
.fontWeight(.bold)
if userName == items.username{
Form{
List(items.items, id: \.self){ item in
Text(item)
}
}
}
}
}
}
struct LoginView_Previews: PreviewProvider {
static var previews: some View {
LoginView()
}
}
解决方案
您可以使用first(where:)
在数组中查找与给定条件匹配的项目(在这种情况下,用户名匹配)。它返回一个可选的,因为不能保证会有一个匹配的项目。
我不得不存根UserModel
,UserModelData
因为你没有包括它们,所以你需要确保类型名称与你所拥有的匹配。
struct UserModel {
var username : String
var password : String
var items : [String]
var type: String
}
struct UserModelData {
var userInformation : [UserModel] = []
}
struct LoginView: View {
var userName = "user"
private var userModelData = UserModelData()
var userInformation : UserModel? {
userModelData.userInformation.first { $0.username == userName }
}
var body: some View{
VStack {
if let userInformation = userInformation {
Text("\(userInformation.username)'s \(userInformation.type)")
.font(.title)
.fontWeight(.bold)
Form {
List(userInformation.items, id: \.self) { item in
Text(item)
}
}
}
}
}
}
推荐阅读
- themes - 如何在 Blazor Web 程序集中集成主题森林主题?
- excel - Excel:查找一个值并指示它是否在其他地方使用 INDEX/MATCH
- reactjs - 您将如何重置 onClick 的无线电输入?反应式
- regex - 正则表达式字母之间任意数量的 _
- visual-studio-code - VS代码查找和替换:选择多行时替换选择会产生意外结果?
- python - 如何从 .txt 文件中提取数据并将其存储在 2 个单独的变量中?
- python - Pandas - 将数据集行从每个人更改为每个操作的最简单方法
- continuous-integration - Gitlab runner 删除构建文件夹
- javascript - 在 Pyppeteer (Python Puppeteer) 中从 page.evaluate 将值返回给 python
- java - Eclipse JUnit 视图