
“猫”
“狗”
“老鼠”
我想用该文件中的字符串填充数组(dico [0] =“Cat”,dico [1] =“Dog”,aso).
我发现了这个,How to call Objective-C’s NSArray class method from within Swift?和Read and write data from text file,但是当我使用这段代码时:
let bundle = NSBundle.mainBundle()let path = bundle.pathForResource("data",ofType: "txt")let dico = NSArray(contentsOffile: path)println("\(dico[0])")println("\(dico.count)") 我得到的只是“零”和“0”.
我想我的文件中的数据不是按照应该的方式编写的,我使用的代码不对,但我无法理解为什么.
而且,当我使用这段代码时,它没关系:
let bundle = NSBundle.mainBundle() let path = bundle.pathForResource("data",ofType: "txt") let dico = Nsstring(contentsOffile: path) println("\(dico)") 问题是我不希望dico成为一个字符串,我希望它是一个数组.
解决方法 这不是arrayWithContentsOffile的工作原理.它期望作为其参数的文件路径,该文件包含由writetofile:atomically:方法生成的数组的字符串表示形式.
出于您的目的,您可以使用第二种方法,并通过在字符串上调用componentsSeparatedByString()来补充.
let bundle = NSBundle.mainBundle()let path = bundle.pathForResource("data",ofType: "txt")let dico = Nsstring(contentsOffile: path).componentsSeparatedByString("\n") 总结 以上是内存溢出为你收集整理的数组 – 使用txt文件中的字符串填充数组全部内容,希望文章能够帮你解决数组 – 使用txt文件中的字符串填充数组所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)