"Ambiguous reference to the membership card" of a particular type

Here is my code. It uses CBUUID , which is from Core Bluetooth. Assume listing v 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 a string representation of the dictionary by calling CBUUID.UUIDString for CBUUID and calling the appropriate NSString constructor for NSData .

I applied the dictionary to a specific type. Why am I getting an 'ambiguous link to member card' here?

+3
source share
1 answer

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

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

Using the extension method

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

from the specified stream 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) ?? "") } } 
+5
source

Source: https://habr.com/ru/post/1238713/


All Articles