【问题标题】:swift2 loading contents of text file into variableswift2将文本文件的内容加载到变量中
【发布时间】:2016-03-22 22:39:31
【问题描述】:

我试图通过从文本文件加载数组来填充数组,然后用换行符分隔文本以制定数组,但是我收到错误“预期表达式”

  var marrCountryList = [String]()
  try!  var text = String(contentsOfFile: "country", encoding: NSUTF8StringEncoding)
  marrCountryList = text.componentsSeparatedByString("\n")

【问题讨论】:

    标签: ios arrays swift swift2 xcode7.2


    【解决方案1】:

    try 位置不对:

    do {
         contentsOfFile = try String(contentsOfFile: "country", encoding: NSUTF8StringEncoding)
    } catch {
        print(error);
        contentsOfFile = nil;
    }
    

    此外,当您使用 try 时,您必须有 docatch

    【讨论】:

    • 使用 try 时不需要 do 和 catch 块。还可以根据操作的成功进行可选分配:var contentsOfFile = try? String(contentsOfFile: "country", encoding: NSUTF8StringEncoding)。然后contentsOfFile 将属于String? 类型。
    猜你喜欢
    • 2023-03-14
    • 1970-01-01
    • 2010-09-13
    • 2018-07-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多