【问题标题】:Load text with variables in it and then print out加载带有变量的文本,然后打印出来
【发布时间】:2014-06-24 01:37:36
【问题描述】:

我可以用 \(variable) 模式打印出变量

    let sayHello = "Hello"
    let contentA = "\(sayHello) bla bla bla"
    println(contentA) //output: Hello bla bla bla

然后我将相同的字符串“\(sayHello) bla bla bla”放在一个文本文件中,并将其加载到一个变量中,然后打印出来。

    let path = NSBundle.mainBundle().pathForResource("file", ofType: "txt")
    var possibleContent = String.stringWithContentsOfFile(path, encoding:NSUTF8StringEncoding, error: nil)

    if let contentB = possibleContent{
        println(contentB)
    }
    //output: \(sayHello) bla bla bla

模式 \(sayHello) 没有获取“sayHello”变量,而是按字面意思输出。

我可以打印类名

    println("\(object_getClassName(contentB))")

“contentA”似乎是 _TtC10Foundation19_NSContiguousString 的实例,而“contentB”似乎是 __NSCFString

如何在文本文件中加载一些包含输出模式的字符串,如 \(variable),然后用 REAL 变量替换它们?

实际上,我的最终目标是将一些 HTML 代码包装起来,例如“<html><header></header><body>\(content)</body></html>”,并将它们构建为 .html 文件。

【问题讨论】:

  • 别以为你能做到。字符串插值发生在评估字符串文字时(即,当您分配 let contentA = ... 时),而不是在打印时。所以从文件加载就像说let contentB = "\\(sayHello)"——你只是在加载实际的字符。
  • XML 或 JSON 文件更接近您想要的。

标签: ios objective-c macos swift


【解决方案1】:

实际上是编译器处理字符串插值。它将序列"Foo \(bar)" 变成"Foo " + bar.description

对于你想要做的事情,你可能不得不回退到+[NSString stringWithFormat:],也许还有位置参数。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-10-31
    • 1970-01-01
    • 2012-06-05
    • 2020-11-30
    • 1970-01-01
    • 2016-05-30
    • 1970-01-01
    相关资源
    最近更新 更多