Long title! I do apologize.
Expected Outcome: Display uniqued string value in UILabel inside a UIView in a stackView. There may be multiple UIViews in the stackView. The stackView lives inside a tableCell. wow….
The views and cells are custom and I am not allowed to create sections. I have to work with what’s in the existing codebase.
Issue I am stuck at trying to get the unique optional string values into the respective UILabels. I have a working extension to get unique items from an array. But I just don’t know where to implement it, to get the unique values I need.
Code:
// Sample Model Structs
struct Parent {
var child: [Child]?
}
struct Child {
var childValue: String?
}
class TableViewCell {
var stackView = UIStackView()
func configureCellFrom(parent: Parent) {
/// Other code lives in the func to use the Parent struct.
if let child = parent.child {
if child.count > 1 {
tableCell.topLabel.text = "Multiple Child Values"
tableCell.ShowChildViewsButton.isHidden = false
for value in child {
let view = CustomUIView()
view.childValue.text = value.childValue.uniqued()
self.stackView.addArrangedSubview(view)
}
}
}
}
}
extension Sequence where Element: Hashable {
func uniqued() -> [Element] {
var set = Set<Element>()
return filter { set.insert($0).inserted }
}
}
Above Problem: Where I placed the uniqued() method, will parse out the individual characters in the string. So I know that it is one level too deep. What’s the best way to achieve my required result?
2
Answers
Try this:
The issue there is that
uniqued
method uses filter method declared onSequence
which will always return an array of theSequence.Element
in the case of aString
an array of characters[Character]
. You can simply initialize a new string with the array or characters or improve that method to support strings as well. To make that method support strings you need to extendRangeReplaceableCollection
. There is a filter method declared onRangeReplaceableCollection
which returnsSelf
therefore if you filter a string it will return another string as I showed in this answer from the same post where you found theuniqued
method you’ve shown in your question:Usage: