-2

Here is my class.

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

What I am trying to do is that my Definition is too long so I want to split it by the commas and display the text as a new line. The code I have printed all elements array in the console but it only prints the last element on the text label. Thanks.

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)"` runs every time; only the last modification won't be overwritten – BallpointBen Aug 06 '19 at 04:39
  • What result do you want? Once the loop is finished, what you do expect to see in the label? – rmaddy Aug 06 '19 at 04:41
  • Unrelated but you are misusing `String(describing:)`. Assuming `definationSplit` is a string then you create a string from a string (String Interpolation) from a string (`String(describing:)`). Most likely `word.text = wordOfDay.word!"`is sufficient. – vadian Aug 06 '19 at 04:42
  • Welcome to SO! A few things about this question; First: What does *split the (Realm?) object* mean exactly? Are you trying to read the property names? Second: What does this have to do with Realm? Third: If you're using an Array, you're not using it with Realm as it does not have a directly managed Array object (It does have collections, which are like arrays). Forth, what is *wordOfDay.Defination*. Last: Can you include what your RealmObject looks like in the question and can you clarify what you're trying to do? – Jay Aug 06 '19 at 18:17
  • Possible duplicate of [Update Text in While Loop Swift](https://stackoverflow.com/questions/57133265/update-text-in-while-loop-swift) – Joakim Danielson Aug 07 '19 at 06:34

1 Answers1

1

If you need the label to have all the elements from array, append the elements to a string. Then set the label text with this string.

var labelText = ""
for (index,element) in completedSplit.enumerated() {
    labelText += "\(index),\(element)"
    print (index,"\u{2022}",element)
}
wordDescription.text = labelText
MjZac
  • 3,476
  • 1
  • 17
  • 28