mythz
mythz

Reputation: 143319

How can I print the description of an unknown type in Swift?

How can I create a dump() Array extension for printing out all elements in an array?

It's a build error when trying to cast to Printable protocol:

extension Array {
    func dump() -> String {
        var s = ""
        for x in self {
            if let p = x as? Printable {
                if s != "" { s += ", " }
                s += p.description
            }
        }
        return s
    }
}

28:26: error: cannot downcast from 'T' to non-@objc protocol type 'Printable'

How can I get a string representation of every element in an Array?

Or is there a way where I can find the Printable elements in an Array?

Upvotes: 2

Views: 503

Answers (2)

Nate Cook
Nate Cook

Reputation: 93276

You can use reduce, as well:

let arr = [1, 2, 3, 4, 5, 6, 7, 8, 9]
arr.reduce("") { $0 == "" ? "\($1)" : "\($0), \($1)" }
// "1, 2, 3, 4, 5, 6, 7, 8, 9"

Upvotes: 0

shucao
shucao

Reputation: 2242

String interpolation?

extension Array {
    func dump() -> String {
        var s = ""
        for x in self {
            let x_str = "\(x)"
            s += x_str
            if !x_str.isEmpty {
                s += ","
            }
        }
        return s
    }
}

Upvotes: 1

Related Questions