将字符串转换为数组字符

时间:2017-07-12 14:24:49

标签: ios swift string sqlite char

我在Xcode 8和Swift 3中创建了一个Puzzle Word项目,我创建了SQLite文件和plist文件,SQLite文件有3列id,问题和答案,所有这些列都是(字符串),当然除了id它是一个整数,我的plist文件是字母数组,我的问题是如何将第3列(答案)从字符串转换为数组字符,如plist没有引号和方括号?! 这是我的代码连接SQLite数据库(DatabaseHelper)

import GRDB

class DatabaseHelper {

    var dbQueue: DatabaseQueue = {

        var db: DatabaseQueue = DatabaseQueue()

        do {

            db = try DatabaseQueue(path: Bundle.main.path(forResource: "testDB", ofType: "sqlite")!)
            print("Connect database sqlite is OK...")

        } catch {

            print("Connect databse fail !!!")

        }

        return db

    }()

    func getDatabase(rowId: Int) -> [DatabaseModel] {

        var listDatabase = [DatabaseModel]()

        dbQueue.inDatabase { db in

            do {

                for row in try Row.fetchAll(db, "select * from QuestionTable where Id = \(rowId)") {

                    let newDatabase = DatabaseModel()
                    newDatabase.id = row.value(named: "Id") as Int
                    newDatabase.ques = row.value(named: "question") as String
                    newDatabase.ans = row.value(named: "answer") as String

                    listDatabase.append(newDatabase)

                }

            } catch {

                print("Get all database fail !!!")

            }

        }

        return listDatabase

    }

}

这段代码是DatabaseModel:

import Foundation

class DatabaseModel: NSObject {

    var id: Int?
    var ques: String?
    var ans = String()

}

此代码从数据库调用:

var dbHelpr = DatabaseHelper()
var listdata = [DatabaseModel]()

let pathRes = Bundle.main.path(forResource: fileName, ofType: fileExt)
        let pathDict = NSDictionary(contentsOfFile: pathRes!)
        var letters : [String] = pathDict?.object(forKey: "Letters") as! [String]
        listdata = dbHelpr.getDatabase(rowId: id)

//        print("\(letters.shuffled())")

        for data in listdata {

            let dataAnswer : String = data.ans

            let dataArrayAnswer = Array(dataAnswer.characters)
            print(dataAnswer)
            let lastLetters = letters.append(String(describing: dataArrayAnswer))
            print(lastLetters)

        }

这是我在控制台中的输出:

enter image description here

1 个答案:

答案 0 :(得分:2)

let myString = "This is my answer"
let chars = Array(myString)

根据问题的标题,我发布此代码,因为它符合从String生成字符数组的要求。

所以根据你的代码,你几乎就在那里,但只删除String的characters属性,因为它已经是Sequence :)

let dataArrayAnswer = Array(dataAnswer)

for char in dataArrayAnswer{
//Prints next char of whatever your string is...
print(char)
}

编辑:另一种方法可能是这样,因为它将Character数组转换为String数组:

let dataArrayAnswer: [String] = dataAnswer.characters.map{String($0)}