gpt4 book ai didi

ios - swift 从此代码中删除可选项

转载 作者:行者123 更新时间:2023-11-29 01:26:11 25 4
gpt4 key购买 nike

下面的代码运行良好,但 address.text 和 phone.text 的值输出为可选。试图通过放置来打开它! (地址.text = results.stringForColumn(“地址”)! phone.text = results.stringForColumn("phone")!),但它没有帮助。

@IBAction func findContact(sender: AnyObject) {
let contactDB = FMDatabase(path: databasePath as String)

if contactDB.open() {
let querySQL = "SELECT address, phone FROM CONTACTS WHERE name = '\(name.text)'"

if let results:FMResultSet = contactDB.executeQuery(querySQL,
withArgumentsInArray: nil) {

if results.next() == true {
address.text = results.stringForColumn("address")
phone.text = results.stringForColumn("phone")
status.text = "Record Found"
} else {
status.text = "Record not found"
address.text = ""
phone.text = ""
}
contactDB.close()
} else {
print("Error: \(contactDB.lastErrorMessage())")
}
}
}

有什么建议吗?

最佳答案

问题是 UITextFieldtext 方法是可选的,所以你的 SQL 可能最终看起来像这样:

SELECT address, phone FROM CONTACTS WHERE name = 'Optional("foo")'

那肯定是不对的。在尝试使用它之前,您需要解包 name.text

但是您根本不应该像那样尝试手动构建 SQL。如果 name.text 包含 ' 字符(例如 Liam O'Flaherety),您就会遇到问题。在 SQL 中使用 ? 占位符(不应与 Swift 中的 ? 混淆)。

然后在 withArgumentsInArray 中解包 name.text:

@IBAction func findContact(sender: AnyObject) {
let contactDB = FMDatabase(path: databasePath as String)
if contactDB.open() {
let querySQL = "SELECT address, phone FROM CONTACTS WHERE name = ?"

if let results = contactDB.executeQuery(querySQL, withArgumentsInArray: [name.text!]) {
if results.next() {
address.text = results.stringForColumn("address")
phone.text = results.stringForColumn("phone")
status.text = "Record Found"
} else {
status.text = "Record not found"
address.text = ""
phone.text = ""
}
} else {
print("Error: \(contactDB.lastErrorMessage())")
}
contactDB.close() // note, this should be outside the `if` for `executeQuery`
}
}

或者,如果使用 Swift 2,您可以:

@IBAction func findContact(sender: AnyObject) {
let contactDB = FMDatabase(path: databasePath as String)
if contactDB.open() {
do {
defer { contactDB.close() }

let querySQL = "SELECT address, phone FROM CONTACTS WHERE name = ?"

let results = try contactDB.executeQuery(querySQL, values: [name.text!])
if results.next() {
address.text = results.stringForColumn("address")
phone.text = results.stringForColumn("phone")
status.text = "Record Found"
} else {
status.text = "Record not found"
address.text = ""
phone.text = ""
}
} catch let error as NSError {
print("Error: \(error.localizedDescription)")
}
}
}

关于ios - swift 从此代码中删除可选项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33988208/

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