swift - 插入从文件加载的字符串

标签 swift

我不知道如何从文件加载字符串并插入该字符串中引用的变量。

假设 filePath 中有一个文本文件,其中包含以下内容:

Hello there, \(name)!

我可以使用以下命令将此文件加载到字符串中:

let string = String.stringWithContentsOfFile(filePath, encoding: NSUTF8StringEncoding, error: nil)!

在我的类(class)中,我已在以下位置加载了一个名称:let name = "George"

我希望这个新字符串使用我的常量插入 \(name),以便其值为 Hello there, George!。 (实际上,文本文件是一个更大的模板,其中有很多需要交换的字符串。)

我看到 String 有一个 convertFromStringInterpolation 方法,但我不知道这是否是正确的方法。有人有什么想法吗?

最佳答案

这不能按您的意愿完成,因为它违背了编译时的类型安全(编译器无法检查您尝试在字符串文件上引用的变量的类型安全)。

作为解决方法,您可以手动定义替换表,如下所示:

// 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 协议(protocol)即可。

为了进一步实现自动化,您可以在单独的 Swift 文件中定义 tokenTable 常量,并使用单独的脚本从包含字符串的文件中提取标记来自动生成该文件。


请注意,对于非常大的字符串文件,此方法可能非常低效(但并不比首先将整个字符串读入内存低效得多)。如果这是一个问题,请考虑以缓冲方式处理字符串文件。

关于swift - 插入从文件加载的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26912859/

相关文章:

ios - 登录时使用所有值打开选项卡栏 Controller

ios - ios 13 中未调用 application(...continue userActivity...) 方法

swift - 如何在 swift4 中将 CNPhoneNumber 转换为字符串?

ios - Core Data 多对多 Swift

ios - 缺少所需的模块 'libxml2'

swift - 取消OperationQueue上的所有操作

ios - 乘以文本字段错误?

ios - swift 图片从URL下载到本地存储

ios - 使用 NotificationCenter 通知 Collection View Cell 更改其 subview - swift

closures - 为什么闭包中的 "unowned self"在 Swift 中无法正常工作?