Swift文本文件到字符串数组 [英] Swift Text File To Array of Strings

查看:123
本文介绍了Swift文本文件到字符串数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道将文本文件读入字符串数组最简单,最干净的方法是什么.

I was wondering what the simplest and cleanest to read a text file into an array of strings is in swift.

文本文件:

line 1
line 2
line 3 
line 4

进入这样的数组:

var array = ["line 1","line 2","line 3","line 4"]

我也想知道如何对这样的结构做类似的事情:

I would also like to know how to do a similar thing into struct like this:

Struct struct{
   var name: String!
   var email: String!
}

因此获取一个文本文件,并将其放入数组的struct中.

so take a text file and put it into struct's in an array.

感谢您的帮助!

推荐答案

首先,您必须阅读文件:

First you must read the file:

let text = String(contentsOfFile: someFile, encoding: NSUTF8StringEncoding, error: nil)

然后使用componentsSeparatedByString方法按行将其分隔:

Then you separate it by line using the componentsSeparatedByString method:

let lines : [String] = text.componentsSeparatedByString("\n")

这篇关于Swift文本文件到字符串数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆