gpt4 book ai didi

arrays - 索引可能不存在(textField)swift xcode

转载 作者:行者123 更新时间:2023-11-30 10:48:51 26 4
gpt4 key购买 nike

基本上,描述是一个可选输入,当存在“葡萄绿”等输入时,会抛出“无效索引范围”等错误。除了添加额外的文本字段之外,还有其他方法可以解决此问题吗?

let fruits = "\(textField.text!)"
let fruitsArray = fruits.split(separator: " ")
let fruitName = "\(fruitsArray[0])"
let fruitColour = "\(fruitsArray[1])"
let description = "\(fruitsArray[2])"

最佳答案

对于这种情况(仍然发现在单个文本字段中要求三个不同的属性不太明智),我建议为 fruit 实现一个模板> 事情。示例:

struct Fruit {
var name: String?
var colour: String?
var description: String?

init?(string: String) {
let array = string.trimmingCharacters(in: .whitespacesAndNewlines).components(separatedBy: " ").filter { !$0.isEmpty }
switch array.count {
case 3...:
fallthrough
case 3:
description = array[2]
fallthrough
case 2:
colour = array[1]
fallthrough
case 1:
name = array[0]

default:
return nil
}
}
}

此时,您可以通过传递字符串来声明一个 Fruit 实例;因此:

let string = "Grapes green"
let fruit = Fruit(string: string)
print(fruit)
// Optional(__lldb_expr_21.Fruit(name: Optional("Grapes"), colour: Optional("green"), description: nil))

关于arrays - 索引可能不存在(textField)swift xcode,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55089007/

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