简体   繁体   中英

Swift returns optional("value") after upgrading to swift 2.1

I am new to swift and just followed a tutorial of sqlite, it runs great but after upgrading to swift 2.1 it appends "optional" to my result, how can I get rid of that?

find data function

    @IBAction func findContact(sender: UIButton)
    {
        if database.open() {
        let querySQL = "SELECT address, phone FROM CONTACTS WHERE name = '\(name.text)'"

            let results:FMResultSet? = database.executeQuery(querySQL,withArgumentsInArray: nil)
            if results!.next() == true {
                if let address1=results!.stringForColumn("address")
                {
                address.text = address1
                }

                phone.text = results!.stringForColumn("phone")
                status.text = "Record Found"
            } else {
                status.text = "Record not found"
                address.text = ""
                phone.text = ""
            }
            database.close()
        } else {
            print("Error: \(database.lastErrorMessage())", terminator: "")
        }
        }

save data function

@IBAction func saveData(sender: UIButton)
        {
            let database = FMDatabase(path: databasePath as String)

            if database.open() {

                let insertSQL = "INSERT INTO CONTACTS (name, address, phone) VALUES ('\(name.text)', '\(address.text)', '\(phone.text)')"

                let result = database.executeUpdate(insertSQL,
                    withArgumentsInArray: nil)

                if !result {
                    status.text = "Failed to add contact"
                    print("Error: \(database.lastErrorMessage())", terminator: "")
                } else {
                    status.text = "Contact Added"
                    name.text = ""
                    address.text = ""
                    phone.text = ""
                }
            } else {
                print("Error: \(database.lastErrorMessage())", terminator: "")
            }

        }

screen shot

问题不在于您选择数据时。问题在于您插入数据时。插入时,您只需在表中插入可选值,如屏幕截图所示的地址字段和电话号码......所以,当时插入时,您需要解开该可选值以避免optional()关键字。

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

you need to add exclamation mark end of the name.text ..

ecs: (name.text!)

May be it will help you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM