3

Here is my code. It uses CBUUID which is from Core Bluetooth. Let's just assume the cast of v is valid.

import UIKit
import CoreBluetooth

func convert(v: AnyObject) -> [String: String] {
    return (v as! [CBUUID: NSData]).map { (uuid, data) in
        (uuid.UUIDString, NSString(data: data, encoding: NSUTF8StringEncoding) ?? "") 
    }
}

The idea is to get the string representation of the dictionary by calling CBUUID.UUIDString for CBUUID and by calling the appropriate NSString constructor for NSData.

I've cast the dictionary to a specific type. Why do I get "ambiguous reference to member 'map'" here?

1 Answers1

5

The error message is misleading. The real problem is that the map() method applied to a dictionary does not return a new dictionary but an array, in your case [(String, String)], See for example What's the cleanest way of applying map() to a dictionary in Swift? for a discussion of that topic.

Another problem is that NSString is not converted to String implicitly, i.e. NSString(data: data, ...) should be replaced by String(data: data, ...).

Using the extension method

extension Dictionary {
    init(_ pairs: [Element]) {
        self.init()
        for (k, v) in pairs {
            self[k] = v
        }
    }
}

from the referenced thread you can return a new dictionary with

func convert(v: AnyObject) -> [String: String] {
    let dict = v as! [CBUUID: NSData]
    return Dictionary(dict.map { (uuid, data) in
        (uuid.UUIDString, String(data: data, encoding: NSUTF8StringEncoding) ?? "") 
    })
}

Alternatively, change the return type to [(String, String)]:

func convert(v: AnyObject) -> [(String, String)] {
    return (v as! [CBUUID: NSData]).map { (uuid, data) in
        (uuid.UUIDString, String(data: data, encoding: NSUTF8StringEncoding) ?? "") 
    }
}
Community
  • 1
  • 1
Martin R
  • 529,903
  • 94
  • 1,240
  • 1,382
  • Thanks. I'd rather not use a dictionary extension, and I can use `(String, String)` instead. So I just tried to change the function return type, but it still returns the same error. Any guidance? –  Nov 21 '15 at 22:52