1

Hi I'm a Swift beginner and I'm trying to make a function that takes an array as input and converts it into a String. The array that I want to use is full of strings.

func arrayToString (_ x:Array<Any>) {
    let y = x.joined(separator: "") // error: Ambiguous reference to member 'joined()'
    return y
}

Can anyone tell me what I'm doing wrong?

1
  • 2
    The elements of x are of type Any, a type you'd generally want to avoid (unless forced to use due to being supplied Any objects from some API at runtime). Is it an option to let x be an array of String instances instead? ([String]). Also, you haven't supplied a return type to your function, so it is inferred to be Void (you want this to be -> String). If you stick with x being [Any], you need to perform an attempted type conversion of each element in x to String prior to calling joined(separator:), e.g. return x.flatMap{ $0 as? String }.joined(separator: ""). Commented Feb 8, 2017 at 16:49

1 Answer 1

1

As per Doc:

extension Array where Element == String {

    /// Returns a new string by concatenating the elements of the sequence,
    /// adding the given separator between each element.
    ///
    /// The following example shows how an array of strings can be joined to a
    /// single, comma-separated string:
    ///
    ///     let cast = ["Vivien", "Marlon", "Kim", "Karl"]
    ///     let list = cast.joined(separator: ", ")
    ///     print(list)
    ///     // Prints "Vivien, Marlon, Kim, Karl"
    ///
    /// - Parameter separator: A string to insert between each of the elements
    ///   in this sequence. The default separator is an empty string.
    /// - Returns: A single, concatenated string.
    public func joined(separator: String = default) -> String
}

It will only work with Array<String>

And your code should be:

func arrayToString (_ x:Array<String>) -> String {
    let y = x.joined(separator: "")
    return y
}

arrayToString(["abc", "123"]) //"abc123"
Sign up to request clarification or add additional context in comments.

1 Comment

Note that the default separator is "", so the function above simply does the same as a call directly to joined() from the array (["abc", "123"].joined()).

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.