Swift 插入从文件加载的字符串
我不知道如何从文件中加载字符串并插入该字符串中引用的变量 让我们假设Swift 插入从文件加载的字符串,swift,Swift,我不知道如何从文件中加载字符串并插入该字符串中引用的变量 让我们假设filePath中的文本文件包含以下内容: Hello there, \(name)! 我可以使用以下命令将此文件加载到字符串中: let string = String.stringWithContentsOfFile(filePath, encoding: NSUTF8StringEncoding, error: nil)! 在我的类中,我在中加载了一个名称:let name=“George” 我希望这个新字符串使用我的
filePath
中的文本文件包含以下内容:
Hello there, \(name)!
我可以使用以下命令将此文件加载到字符串中:
let string = String.stringWithContentsOfFile(filePath, encoding: NSUTF8StringEncoding, error: nil)!
在我的类中,我在中加载了一个名称:let name=“George”
我希望这个新字符串使用我的常量插入\(名称)
,使其值为你好,乔治代码>。(实际上,文本文件是一个大得多的模板,其中包含大量需要交换的字符串。)
我看到String
有一个convertFromStringInterpolation
方法,但我不知道这样做是否正确。有人有什么想法吗?没有内置的机制,你必须自己创造
下面是一个非常初级版本的示例:
var values = [
"name": "George"
]
var textFromFile = "Hello there, <name>!"
var parts = split(textFromFile, {$0 == "<" || $0 == ">"}, maxSplit: 10, allowEmptySlices: true)
var output = ""
for index in 0 ..< parts.count {
if index % 2 == 0 {
// If it is even, it is not a variable
output += parts[index]
}
else {
// If it is odd, it is a variable so look it up
if let value = values[parts[index]] {
output += value
}
else {
output += "NOT_FOUND"
}
}
}
println(output) // "Hello there, George!"
var值=[
“姓名”:“乔治”
]
var textFromFile=“您好,!”
var parts=split(textFromFile,{$0==“”},maxSplit:10,allowEmptySlices:true)
var output=“”
对于0..
根据您的用例,您可能必须使其更加健壮。这不能按您的意愿完成,因为它在编译时不利于类型安全(编译器无法检查您试图在字符串文件上引用的变量的类型安全)
作为一种解决方法,您可以手动定义替换表,如下所示:
// Extend String to conform to the Printable protocol
extension String: Printable
{
public var description: String { return self }
}
var string = "Hello there, [firstName] [lastName]. You are [height]cm tall and [age] years old!"
let firstName = "John"
let lastName = "Appleseed"
let age = 33
let height = 1.74
let tokenTable: [String: Printable] = [
"[firstName]": firstName,
"[lastName]": lastName,
"[age]": age,
"[height]": height]
for (token, value) in tokenTable
{
string = string.stringByReplacingOccurrencesOfString(token, withString: value.description)
}
println(string)
// Prints: "Hello there, John Appleseed. You are 1.74cm tall and 33 years old!"
您可以将任何类型的实体存储为tokenTable
的值,只要它们符合Printable
协议
为了进一步实现自动化,您可以在单独的Swift文件中定义tokenTable
常量,并通过使用单独的脚本从包含字符串的文件中提取令牌来自动生成该文件
请注意,对于非常大的字符串文件,这种方法可能效率很低(但效率不会比首先将整个字符串读入内存的效率低很多)。如果这是一个问题,考虑以缓冲方式处理字符串文件。