简体   繁体   English

如何在Swift 3中将字符串转换为数组

[英]How to convert string to array in Swift 3

I am inserting an Array into my database as a String and after fetching it I want it to convert it again to Array . 我将一个Array作为String插入到我的数据库中,并在获取它后希望它再次将其转换为Array So that I can fetch my values again and I can do next operation. 这样我可以再次获取值,然后执行下一个操作。

Here below is my array inserting into database(TestQuestion) as a String : 下面是我的数组作为String插入数据库(TestQuestion)的String

 let testQuestionModel : TestQuestion = NSEntityDescription.insertNewObject(forEntityName: "TestQuestion", into: AppDelegate.getContext()) as! TestQuestion
testQuestionModel.optionsArray = "\(question["options"] as! NSArray)"

Example: String Array I am getting from Database 示例:我从数据库获取的字符串数组

(\\n \\"Rahul Abhyankar\\",\\n \\"Pinkesh Shah\\",\\n \\"Ramanan Ganesan\\",\\n \\"Dr. Marya Wani\\",\\n \\"\\",\\n \\"\\"\\n)". (\\ n \\“ Rahul Abhyankar \\”,\\ n \\“ Pinkesh Shah \\”,\\ n \\“ Ramanan Ganesan \\”,\\ n \\“ Marya Wani博士”,\\ n \\“ \\”,\\ n \\“ \\ “\\ n)的”。

Here is 4 options you can see this is my string after fetching from Database. 这是4个选项,从数据库中获取后,您可以看到这是我的字符串。

1) Rahul Abhyankar. 1)拉胡尔·阿比扬卡(Rahul Abhyankar)。

2) Pinkesh Shah. 2)Pinkesh Shah。

3) Ramanan Ganesan. 3)Ramanan Ganesan。

4) Dr. Marya Wani. 4)Marya Wani博士。

Now how can I convert it into array? 现在如何将其转换为数组?

I tried some methods. 我尝试了一些方法。

let arr = NSArray(object: quetion.optionsArray!). 

But I am getting only one object. 但是我只得到一个对象。 How can I get my array values same as previous from this string array? 如何从此字符串数组中获取与以前相同的数组值?

I don't know about the actual type of the "option" in your code, so I set up a fake Elem struct to represent it. 我不知道代码中“选项”的实际类型,所以我建立了一个假的Elem结构来表示它。 The remaining logic is independent of the type as long as you provide a conversion logic to and from String . 只要您提供往返String的转换逻辑,其余逻辑就与类型无关。

struct Elem {
    // let's say this is your element type in your array
    let foo: Int;
}

extension Elem: CustomStringConvertible {
    var description: String {
        // provide a logic to convert your element to string
        return "\(foo)";
    }
}

let arrayToSave = [
    Elem(foo: 1),
    Elem(foo: 2),
    Elem(foo: 3)
]

extension Elem {
    init(string: String) {
        // provide a function to construct your element type from a string
        self.init(foo: Int(string)!)
    }
}

let stringToSave = arrayToSave.map { $0.description }.joined(separator: "|")

// save this string

// at some point retrieve it from database, which hopefully same as the saved one

let retrivedString = stringToSave;

let retrivedArray = retrivedString.split(separator: "|").map { Elem(string: String($0)) }

print(retrivedArray) // [1, 2, 3]

Here below is my array inserting into database ( TestQuestion ) as a String : 下面是我的数组以String插入数据库( TestQuestion ):

 let testQuestionModel : TestQuestion = NSEntityDescription.insertNewObject(forEntityName: "TestQuestion", into: AppDelegate.getContext()) as! TestQuestion testQuestionModel.optionsArray = "\\(question["options"] as! NSArray)" 

No , and No .
You are using -description method of an array to save it. 您正在使用数组的-description方法保存它。 Clearly no. 显然没有。 What's wrong? 怎么了? Apple can't affirm that in next OS release, it won't add an extra character. 苹果不能肯定在下一个操作系统版本中,它不会添加额外的字符。 In some more complex cases, it's added <NSArray <0x address> or stuff similar like that. 在某些更复杂的情况下,会添加<NSArray <0x address>或类似的内容。

Suggestion 1: 建议1:
Modify your entity to have an ARRAY (or usually a Set) of String. 修改您的实体,使其具有字符串的ARRAY(或通常为Set)。 Learn about Core-Data relationship (but that's clearly a DataBase basic knownledge). 了解核心数据关系 (但这显然是数据库的基本知识)。 A relationship one to many should be the thing to do.You could even keep in memory what were the choices, by adding for creating the entity Options, with a String property name (name of the option), another one boolean isChecked , etc. 要做一对多的关系,您甚至可以在内存中保留选择的内容,方法是添加用于创建实体选项的选项,其中包含String属性name (选项名称),另一个布尔值isChecked等。

Suggestion 2: 建议2:
If you have a limited number of options (like says one to 5), add 5 options string to your entity, and iterate to set them 如果您的选项数量有限(例如说一到五个),请向您的实体中添加5个选项字符串,然后重复进行设置

testQuestionModel.option1 = question["option"][0]
testQuestionModel.option2 = question["option"][1] (if it's of course not out of range for the array)
...

Suggestion 3: Not really recommended (in my opinion it's missing the whole advantage of the database, especially fetch and predicates, on previous sample you could fetched easily which options were checked), but if you still want to save them as a String, save them as JSON (ie. stringified). 建议3:并不是真的推荐(我认为它缺少数据库的全部优势,尤其是在获取和谓词上,在以前的示例中,您可以轻松获取选中了哪些选项),但是如果您仍然想将它们另存为字符串,请保存它们作为JSON(即已字符串化)。 In pseudo code (I'm not sure about the exact syntax, there are no fail safe like try/catch, optional/wrapping): 在伪代码中(我不确定确切的语法,没有像try / catch,optional / wrapping这样的故障保护):

let options = questions["options"] as [String]
let jsonData = JSONSerialization.data(withJSONObject: (question["options"], options:[])
let jsonString = String.init(data:jsonData encoding:.utf8)

To retrieve them: 要检索它们:

let options = JSONSerialization.jsonObject(with data: myJSONString.data(encoding:.utf8), options:[]) as [String]

done using Library SwiftyJSON. 使用Library SwiftyJSON完成。

 if let dataFromString = yourString?.data(using: String.Encoding.utf8, allowLossyConversion: false) {
        do{
            let json = try JSON(data: dataFromString)
            print(json)
            let arrayValue = json.rawValue as! NSArray

            print(arrayValue)
        } catch{
            print(error.localizedDescription)

        }
    }

Source: https://github.com/SwiftyJSON/SwiftyJSON 来源: https : //github.com/SwiftyJSON/SwiftyJSON

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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