【发布时间】:2019-02-03 19:58:39
【问题描述】:
我试图有一个按钮来保存文本字段中的内容,然后将它们添加到它们的数组中,然后对数组进行排序。但是,无论何时进行排序,我的数组中的前两个字符串都不会排序,但第三个字符串和其他保存的字符串都会排序。
这是数组
//Array holding Names
var names: [String] =
[
"Alexander Jones",
"Tony Stark",
"cap"
]
//Array holding emails
var emails: [String] =
[
"alex@fiu.edu",
"Tony@Stark.com",
"cap@ca"
]
//Index to move through arrays
var index: Int = 0
这里是按钮功能(请忽略它的更新部分,我正在尝试在解决这个问题之前让排序工作
@IBAction func updateButtonPressed(_ sender :UIButton)
{
var name = nameField.text
let email = emailField.text
print("0 \(names)")
print("0 \(emails)")
//if the email or name isn't modified
//assume user is updating card
if (name==names[index]) || (email==emails[index])
{
//if both textfileds are same as index, update since values will stay the same
//if one filed is updated at the current index, it will be changed at the index and
//still match the index of other array
names[index]=name!
emails[index]=email!
}
else
{
//if user puts a new value for both
//we assume it is a new entry and add it to list
names.append(name!)
emails.append(email!)
print("After Add")
print("1 \(names)")
print("1 \(emails)")
//sort list in alphabetical after each update/save
names = names.sorted(by: <)
print("After sorted by name")
print("2 \(names)")
print("2 \(emails)")
//find index new name is sorted too
//and place new email in same index
//of emailarray
let newindex = names.index(of:name!)
//emails.remove(at: index)
emails.insert(email!, at: newindex!)
print("After email insert")
print("3 \(names)")
print("3 \(emails)")
}
}
【问题讨论】:
-
为什么不使用包含一个人的姓名和电子邮件的结构而不是两个数组?代码相当繁琐。