componentsByString for NSMutableSet in Swift 3.0

278 views Asked by At

I have label and NSMutable Set.

I want to assign my set value to label.text.

  @IBOutlet var location: UILabel!
 var mutSet:NSMutableSet = NSMutableSet()

        self.location.text = **mutSet.allObjects.componetsJoinedByString("\n")**

mutSet.allObjects.componetsJoinedByString("\n") throws compile time error similarly I have tried joined , it also throws compile time error.

Please provide me alternative way in Swift

1

There are 1 answers

2
vadian On

First of all to answer your question: You have to write

(mutSet.allObjects as! [String]).joined(separator: "\n")

NS(Mutable)Set lacks any type information. You have to cast the type to actual [String]


It's highly recommended to use native Set and generally you are discouraged from using NSMutable... types if there is a native counterpart.

var mutSet = Set<String>(["a", "b", "c"])

You can append (actually insert) an item - a set is unordered

mutSet.insert("d")

or an array of items

mutSet.formUnion(["c", "d", "f"])

Joining is much shorter than in Foundation NSMutableSet

mutSet.joined(separator: "\n")

or sorted joined

mutSet.sorted().joined(separator: "\n")