我正在研究Swift 4。
要求:我有一个字符串:
var inputString = "Today is very bright day"
我有一个包含字符串键值对的文件。
{
"Birthday": ["brand day", "burn day", "bright day", "brick daya"],
"Temporary": ["tempora", "temporar", "tempura"]
}
需要的数学:在应用程序中,如果inputString是"Today is very bright day"
,我需要检查此字符串是否包含键值对文件中的任何值,并将该事件替换为键。
例如:在上面的示例中:inputString = "Today is very bright day"
将它与文件匹配。
用生日代替生日,以便inout字符串变为
inputString = "Today is very birthday"
。
有没有办法做到这一点?键值文件可能很大。
答案 0 :(得分:1)
你可以使用强力解决方案,它将是2 for循环,我正在努力增强它
var size = 500;
var Xpos = Math.floor(Math.random() * size);
var Ypos = Math.floor(Math.random() * size);
var dist = Math.hypot(Xpos - size / 2, Ypos - size / 2);
答案 1 :(得分:0)
我认为无论如何都必须遍历每个键值配对的每个列表,但这是替换子串的基本方法。
import Foundation
let replacer = "Birthday"
let replacees = ["brand day", "burn day", "bright day", "brick daya"]
var inputString = "Today is very bright day"
for phrase in replacees {
inputString = inputString.replacingOccurrences(of: phrase, with: replacer)
}
print(inputString) //should print "Today is very birthday"
答案 2 :(得分:0)
无论如何我都无法实现你想要的东西,而无需迭代你的键值列表,但这是一个解决方案。我不确定它是否有效,但你可以尝试一下。
if let path = Bundle.main.path(forResource: "fileName", ofType: "json") {
do {
let data = try Data(contentsOf: URL(fileURLWithPath: path), options: .mappedIfSafe)
let jsonResult = try JSONSerialization.jsonObject(with: data, options: .allowFragments)
if let keyValueArray = jsonResult as? [String: [String]]{
var inputString = "Today is very bright day"
for (key, value) in keyValueArray {
let regex = "\\b" + value.joined(separator: "|\\b")
inputString = inputString.replacingOccurrences(of: regex, with: key, options: .regularExpression, range: nil)
}
print(inputString)
}
} catch {
return
}
}