stestagg
stestagg

Reputation: 81

Swift map array of arrays to array of tuples - 'map' produces [T], not the expected

I'm sure I'm doing somethings silly here, but don't understand what.

The goal is to map an array of arrays (in json as: [[0.1, 0.2, "Text"], ...]) to an array of Tuples of CGPoint/String pairs: [CGPoint(0.1, 0.2), "Text"]

I have a container class that looks like this:

struct Foo {
    let text: [(CGPoint, String)]

    init(json: [String: Any]) throws {
      let textraw = (json["text"] ?? []) as! [[Any]]

      text = textraw.map {  // <- Error here
        (a) -> (CGPoint, String) in
        return (CGPoint(a[0] as! CGFloat, a[1] as! CGFloat), a[2] as! String)
      }
   }
}

The error message is:

'map' produces '[T]', not the expected contextual result type '[(CGPoint, String)]'

I can't see why swift can't work out that the block returns the correct type here?

Upvotes: 1

Views: 574

Answers (2)

stestagg
stestagg

Reputation: 81

OK, I worked it out, the error message here is really unfortunate.

I managed to forget how the CGPoint constructor works - CGPoint(x:, y:) not CGPoint(,). This was the real error. Fixing the relevant lineto read:

return (CGPoint(x: a[0] as! CGFloat, y: a[1] as! CGFloat), a[2] as! String)

Resolved the issue.

Upvotes: 1

idmean
idmean

Reputation: 14865

You did not indicate which version of Swift you are using but your code seems fine with Swift 3 and 4 except for that you are missing the argument labels for the CGPoint initialiser:

return (CGPoint(x: a[0] as! CGFloat, y: a[1] as! CGFloat), a[2] as! String)

Upvotes: 2

Related Questions