【问题标题】:Swift array only printing the last elementSwift数组只打印最后一个元素
【发布时间】:2019-08-06 04:35:14
【问题描述】:

这是我的课。

class dictionaryWord Object
{
    @objc dynamic var word: String?
    @objc dynamic var Defination: String?
    @objc dynamic var dateCreated: Date?  
}

我想要做的是我的定义太长,所以我想用逗号分隔它并将文本显示为新行。我打印了所有元素的代码 控制台中的数组,但它只打印文本标签上的最后一个元素。谢谢。

let definationSplit = "\(String(describing: (wordOfDay.Defination!)))"
let completedSplit: [String] = definationSplit.components(separatedBy: ",")

word.text = "\(String(describing: (wordOfDay.word!)))"

for (index,element) in completedSplit.enumerated() {
    wordDescription.text = "\(index),\(element)"
    print (index,"\u{2022}",element)
}

【问题讨论】:

  • wordDescription.text = "\(index),\(element)" 每次运行;只有最后的修改不会被覆盖
  • 你想要什么结果?循环完成后,您希望在标签中看到什么?
  • 不相关,但您误用了String(describing:)。假设definationSplit 是一个字符串,那么您从一个字符串(字符串插值)从一个字符串(String(describing:))创建一个字符串。很可能word.text = wordOfDay.word!"就足够了。
  • 欢迎来到 SO!关于这个问题的一些事情;第一:拆分(领域?)对象究竟是什么意思?您是否正在尝试读取属性名称?第二:这和Realm有什么关系?第三:如果您使用的是 Array,则不会将它与 Realm 一起使用,因为它没有直接管理的 Array 对象(它确实有集合,就像数组一样)。第四,什么是wordOfDay.Defination。最后:您能否在问题中包含您的 RealmObject 的外观,您能否阐明您正在尝试做什么?

标签: arrays swift realm


【解决方案1】:

如果您需要标签包含数组中的所有元素,请将元素附加到字符串。然后用这个字符串设置标签文本。

var labelText = ""
for (index,element) in completedSplit.enumerated() {
    labelText += "\(index),\(element)"
    print (index,"\u{2022}",element)
}
wordDescription.text = labelText

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-26
    • 2017-12-27
    • 1970-01-01
    • 1970-01-01
    • 2019-09-12
    相关资源
    最近更新 更多