我遇到了一个问题,我试图用 firebase 表中的值填充全局变量;问题是我需要用引号分隔数据。
这是目前的数据:
var data1 = [
quoteData(sectionType: "For You", quotes: ["Categories/General.png"]),
quoteData(sectionType: "Free Today", quotes: [myFreeItems]),
quoteData(sectionType: "Inspiration", quotes: ["Categories/Feeling Sassy.png"])
]
如您所见,myFreeItems 是一个 var,通过以下代码从 firebase 表中提取 var 数据:
override func viewDidLoad() {
super.viewDidLoad()
let myRef = myRef.reference().child("Quotes/Free Today")
myRef.keepSynced(true)
// observe value of reference
myRef.observe(.value, with: { snapshot in
for item in snapshot.children {
let mItem = FreeItem(snapshot: item as! DataSnapshot)
if mItem.act == "Y" {
self.newItems.append(mItem)
}
}
for index in self.newItems {
if index.act == "Y" {
var tempVal = "Categories/"
if self.subCount <= self.newItems.endIndex - 1 {
print(self.subCount)
print(self.newItems.endIndex)
if self.subCount < self.newItems.endIndex - 1 {
tempVal += index.nm + ".png"
print(tempVal)
self.tmpVal += "\"" + tempVal + "\"" + ","
print(self.tmpVal)
} else {
tempVal += index.nm + ".png"
print(tempVal)
self.tmpVal += "\"" + tempVal + "\""
print(self.tmpVal)
}
self.subCount += 1
}
}
}
myFreeItems = self.dougie
print(myFreeItems)
})
到目前为止,一切都很好。当我打印声明时,我得到以下信息:
"Categories/Death.png","Categories/Confidence.png","Categories/Sassy.png"
正是我想要的。
现在问题来了。我在另一个设置中引用这个变量“myFreeItems”:
var data1 = [
quoteData(sectionType: "For You", quotes: ["Categories/General.png"]),
quoteData(sectionType: "Free Today", quotes: [myFreeItems])
]
当我打印出来时,我得到这个:
Motivation.quoteData(sectionType: "Free Today", quotes: ["\"Categories/Death.png\",\"Categories/Confidence.png\",\"Categories/Sassy.png\""]),
它正在拾取转义字符。我需要看到以下内容:
quoteData(sectionType: "Free Today", quotes: ["Categories/Death.png", "Categories/Confidence.png", "Categories/Sassy.png"])
任何帮助将不胜感激。我也尝试过使用增强的哈希标记#,但这也不起作用。
问题是您需要将
myFreeItems
声明为 [String]
而不是仅仅 String
。 viewDidLoad
中的逻辑应该填充字符串数组,而不是创建带有引号和逗号的单个字符串。
将
var myFreeItems = ""
(或任何你拥有的)更改为 var myFreeItems = [String]()
然后更新
for
中的viewDidLoad
循环:
for index in self.newItems {
if index.act == "Y" {
if self.subCount <= self.newItems.endIndex - 1 {
let tempVal = "Categories/" + index.nm + ".png"
myFreeItems.append(tempVal)
self.subCount += 1
}
}
}
删除线:
myFreeItems = self.dougie
最后,改变:
quoteData(sectionType: "Free Today", quotes: [myFreeItems])
至:
quoteData(sectionType: "Free Today", quotes: myFreeItems)