Adding text to a loop in Swift

I need to add an array of strings and finally get one string, which will be displayed in UILabel in the following format.

Action1 | Action2 | Action3 | Action4

 for action in actions { actionLabel.text += "\(action.name) |" } 

This gives me the following error.

 'String?' is not identical to 'UInt8'. 

Any reason for this error? Is there any other way to do this?

Thanks.

+5
source share
2 answers

This is one of the quick messages with crypto errors. As far as I can tell, since the left and right sides are not the same ( Optional<String> vs String ), it is best to assume that you meant that both sides were UInt8 .

To understand that UILabel.text is optional, you can do something long:

 actionLabel.text = (actionLabel.text ?? "") + "\(action.name) |" 

This gets the current value or an empty string and adds text. You can also avoid the problem functionally:

 actionLabel.text = join(" | ", map(actions, { $0.name })) 

Update

Regarding an iterative solution with additional | at the end of the "", I tried to illustrate the solution of only the line causing the error. Your published code also makes the assumption that actionLabel was initially empty and has some (probably insignificant) performance overhead when setting label text several times.

A complete iterative approach might look something like this:

 var text = "" for action in actions { if text.isEmpty { text = action.name } else { text += " | \(action.name)" } } actionLabel.text = text 

Mapping and concatenation are such common operations that most languages ​​have clean, concise ways to do this without iteration. For example, I would recommend the following in Objective-C:

 actionLabel.text = [[actions valueForKeyPath:@"name"] componentsJoinedByString:@" | "]; 
+14
source

text The property may optionally be nil . You can use the optional chain for this. Also set the initial text before going through the loop.

 if actionLabel.text == nil { actionLabel.text = "" } for action in actions { actionLabel.text? += "\(action.name) |" } 
+5
source

Source: https://habr.com/ru/post/1203190/


All Articles