To convert a set of strings to a set of floats in Swift, you can use the compactMap
method to transform each string into a float and filter out any nil values, and then create a new set from the resulting array.
In this example,
stringSet1
using the Set
constructor, which contains the string values "1.1"
, "2.2"
, and "3.3"
.compactMap
method on stringSet1
to transform each string into a float using the closure Float($0)
. This closure returns an optional float, so compactMap
filters out any nil values.Set
constructor, resulting in a set of floats named floatSet1
.print
.let stringSet1: Set<String> = ["1.1", "2.2", "3.3"]
let floatSet1 = Set(stringSet1.compactMap { Float($0) })
print(floatSet1)
Set(3.3, 2.2, 1.1)
In this example,
stringSet2
using the Set
constructor, which contains the string values "1.1"
, "hello"
, "2.2"
, "3.3"
, and "world"
.compactMap
method on stringSet2
to transform each string into a float using the closure Float($0)
. This closure returns an optional float, so compactMap
filters out any nil values.Set
constructor, resulting in a set of floats named floatSet2
.print
.let stringSet2: Set<String> = ["1.1", "hello", "2.2", "3.3", "world"]
let floatSet2 = Set(stringSet2.compactMap { Float($0) })
print(floatSet2)
Set(3.3, 2.2, 1.1)
In this tutorial, we learned How to Convert a Set of Strings to a Set of Floats in Swift language with well detailed examples.