说我在这里有一个字符串:
var fullName: String = "First Last"
Run Code Online (Sandbox Code Playgroud)
我想在白色空间上拆分字符串,并将值分配给它们各自的变量
var fullNameArr = // something like: fullName.explode(" ")
var firstName: String = fullNameArr[0]
var lastName: String? = fullnameArr[1]
Run Code Online (Sandbox Code Playgroud)
此外,有时用户可能没有姓氏.
我从一个csv文件中读取,并希望使用stringWithContentsOfFile分割我得到的长字符串,这是一个多行字符串,各个行代表csv文件中的行.我该怎么做呢?
对于我的新项目.我已将我的csv文件内容加载为NSString.首先,我需要通过换行拆分它,然后用逗号分隔每一行.我怎么能循环这一切?请你帮助我好吗?
CSV内容
"^ GSPC",1403.36,"4/27/2012","4:32 pm",+ 3.38,1400.19,1406.64,1397.31,574422720"^ IXIC",3069.20,"4/27/2012","5:30 pm " + 18.59,3060.34,3076.44,3043.30,0
ViewController.m
NSString* pathToFile = [[NSBundle mainBundle] pathForResource: @"quotes" ofType: @"csv"];
NSString *fileString = [NSString stringWithContentsOfFile:pathToFile encoding:NSUTF8StringEncoding error:nil];
if (!fileString) {
NSLog(@"Error reading file.");
}
NSArray *array = [fileString componentsSeparatedByCharactersInSet:[NSCharacterSet newlineCharacterSet]];
for(int i=0; i<[array count]; i++){
//
}
Run Code Online (Sandbox Code Playgroud) enumerateLinesSwift String类型的函数声明如下:
enumerateLines(body: (line: String, inout stop: Bool) -> ())
Run Code Online (Sandbox Code Playgroud)
据我了解,这个声明表示:"enumerateLines是一个函数采取关闭,body,这是交给两个变量,line和stop,并返回void."
根据Swift编程语言书,我相信我应该能够以enumerateLines一个简洁的简洁方式调用尾随闭包,如下所示:
var someString = "Hello"
someString.enumerateLines()
{
// Do something with the line here
}
Run Code Online (Sandbox Code Playgroud)
..但是会导致编译错误:
Tuple types '(line: String, inout stop: Bool)' and '()' have a different number of elements (2 vs. 0)
那么我尝试显式地放入参数,并取消尾随闭包:
addressString.enumerateLines((line: String, stop: Bool)
{
// Do something with the line here
})
Run Code Online (Sandbox Code Playgroud)
...但是会导致错误:
'(() -> () -> $T2) -> $T3' is …