How to resolve 'Type of expression is ambiguous without more context' error with recursive function

I have the following function:

static func deepMerge(_ target: [AnyHashable:Any], _ source: [AnyHashable:Any])throws -> [AnyHashable:Any] {
    var mutTarget = target
        
    mutTarget.merge(source) { (target, source) in
        if target is [AnyHashable:Any] && source is [AnyHashable:Any] {
            return deepMerge(target, source)
        } else {
            return source
        }
    }
        
    return mutTarget
}

The recursive call to deepMerge(target, source) is raising the Type of expression is ambiguous without more context error in XCode. How best can I resolve this?

I'm not facing that error with the last development snapshot. At that line I got three errors, namely:

  • for target
    Cannot convert value of type 'Any' to expected argument type '[AnyHashable : Any]'
    Insert ' as! [AnyHashable : Any]'
    
  • for source
    Cannot convert value of type 'Any' to expected argument type '[AnyHashable : Any]'
    Insert ' as! [AnyHashable : Any]'
    
  • for deepMerge
    Call can throw, but it is not marked with 'try' and the error is not handled
    

You're also missing a try at the third line, since muTarget.merge can throw.

Does this snippet give you the same error?

static func deepMerge(
  _ target: [AnyHashable: Any], _ source: [AnyHashable: Any]
) throws -> [AnyHashable: Any] {
  var mutTarget = target
    
  try mutTarget.merge(source) { target, source in
    guard let target = target as? [AnyHashable: Any],
          let source = source as? [AnyHashable: Any] else { return source }
    return try deepMerge(target, source)
  }
  
  return mutTarget
}
1 Like