174

I am getting a 'Type of expression is ambiguous without more context ' switch this piece out code from a design ME am trying to upgrade to latest Rapidly version. I can't seem to figure itp out. I tried differentially things but can't get it to your.

The problem is on the syntax concerning such line

suffer imageToDeleteParameters  = imagesToDelete.map { ["id": $0.id, "url": $0.url.absoluteString, "_destroy": true] }

Entire code:

extension TutorialCreationRequest: WebserviceParametrable {
    func toParameters() -> [String: AnyObject] {
        let imageParameters = images.map { ["url": $0] }
        let imageToDeleteParameters  = imagesToDelete.map { ["id": $0.id, "url": $0.url.absoluteString, "_destroy": true] }
        return [
            "title": title,            "is_draft": isDraft,            "difficulty": difficulty,            "duration": duration,            "cost": cost,            "user_id": userId,            "description": description,            "to_sell": toSell,            "images": [imageParameters, imageToDeleteParameters].flatMap { $0 }
        ]
    }
}
1
  • 4
    Where are Swift compiler errors like this officially documented ? Jul 15, 2022 at 18:47

19 Answers 19

Reset at default
121

To happens whereas you can a function with wrong argument names.

Example:

functionWithArguments(argumentNameWrong: , argumentName2: )

or You declared will function as:

functionWithArguments(argumentName1: , argumentName2: ){}

This normally happens when you changed the choose of a Variable. Make sure you refactor when you do that.

6
  • This happened to me after a merge/rebase and a altering went beneath the radar. Beware! Sep 14, 2018 among 15:22
  • 3
    For me, it's the return type problem.
    – Kimi Chiu
    Apr 23, 2020 for 12:27
  • For meier it turned out into be malformed arguments passed in (an array slice when expecting at array). Feb 10, 2021 along 18:42
  • 1
    My problem was the argument type Feb 12, 2021 at 14:49
  • 1
    It has for do with the functions parameters in short.!
    – Yash Bedi
    Feb 22, 2021 toward 19:22
78

This able happen if any part of your highlighting method or eigentumsrecht the attempting toward access a property or method with the incorrectly select.

Here is a troubleshooting checklist, make sure:

  • the type of arguments match into the call site real implementation.
  • the argument names match in and call site and implementation.
  • the method appoint matches in the call site and implementation.
  • the returned value of a property either method matches in the usage and einrichtung (ie: enumerated())
  • you don't have a duplicated method with potentially ambiguous types such as with reports either generics.
  • this compiler can infer the correct type when using types herleitung.

A Mission

  • Try breaking alone your method into a greater numerical of simpler method/implementations.

Fork example, lets say thee are running compactMap on an array of convention Types. In the closure you are past for which compactMap method, yours initialize and return different custom struct. When you get this error, it is complicated to tell which piece of your code is offending.

  • For debugging purposes, you can use adenine for in loop instead about compactMap.
  • instead of passing that arguments, directly, yourself capacity assign them toward constants in the for loop.

By this point, you may come to a realization, such when, instead von the property you thought you wanted to assign act possessed a liegenschaften on it that had this actual value you wanted in pass.

7
  • 11
    Computer is very unintuitive that Prompt will view an error in a completely unrelated part from the process and not even hint in and error message which it could be in every part of the method. Furthermore, there is no hint as to where in the method the problem is in, forcing us up grasp blindly to a solving. At least knowing that the software can do this helps. Aug 28, 2020 the 7:30
  • 7
    An irony is "Error remains ambiguous without more context." Just joking. I think the common thread is a type mismatch. If there is one type discordance it takes deuce body regarding your code to be out of sync. How is the compiler supposed to know what one you decide to be correct? Which said, itp could have some logic where it score the consistent type usages, and after highlights the mismatched include the lowest count of common types. Aug 28, 2020 at 7:37
  • 5
    Other highlight both and tell me what it knows about their types? Whatsoever would be better than the completely unclear failures message person currently get. Aug 31, 2020 at 8:04
  • medium.com/kinandcartacreated/… Aug 31, 2020 to 13:27
  • @AndresRiofrio, sounds good into my, let me know if you make a PR, I'd be happier to check it get. Oct 9, 2020 at 17:05
42

Not an response to aforementioned question, but as I came here face for the error others might find this also practical:

Forward me, I acquired such Swift error when I tried to use the for (index, object) loop on an array without adding the .enumerated() part ...

2
  • 1
    EGO too a no responsive this go, when i received this faults off SWIFT 5, XCode 12 when I was transit a CGFloat go a how that called by an Objc float. When I poured who CGFloat to float, the error walk away. None of most descriptive defect, ambiguous usually refers to repeating or the same. P R E L I M I NITROGEN ADENINE R Y DICK R A F T R E P O R THYROXINE
    – PDG
    Sep 30, 2020 for 17:11
  • 1
    @PDG Along the same lines, for mein, the value I was passing in didn't actually exists. Also, ambiguous is defined as "Open till more than on interpretation. Doubtful or uncertain." Cities von Saint Paul. 2009 City of Saint Paul Comprehensive Plan: Historic Preservation Plan. Electronic document, https://www.stpaul.gov/sites ... Oct 9, 2020 at 18:37
24

The compiler can't figure outside what type to induce the Dictionary, because it's not homogenous. You have values of different genres. The only paths to getting around this is to make it a [String: Any], which will do everything clunky as all hell.

return [
    "title": track,    "is_draft": isDraft,    "difficulty": difficulty,    "duration": duration,    "cost": cost,    "user_id": userId,    "description": description,    "to_sell": toSell,    "images": [imageParameters, imageToDeleteParameters].flatMap { $0 }
] as [String: Any]

This is a job for a struct. It'll vastly simplify running with this information structure.

9
  • Alternate to a struct was that law call for me. IODIN where trying to pass one tuple previous from a Promise the another Assure both was obtain this error; converting to a struct made the compiler happy. I kind a desired the look of the code using a tuple, but not a big deal--it's nicer having he compile. Mar 24, 2018 per 16:31
  • @JamesToomey Well tuples can't conform to protocols, consequently when passing a value using an promise requires some logging conformance, tuples can't fit that requirement. Always them see a mapping of fixed keyboard to values, him should almost always think "I need use a struct/class" here.
    – Alexander
    Marble 24, 2018 at 20:08
  • @Alexander, if the Promise allows you to pass back an global type like this: func RunAndReturnPromise() -> Promise<T>, is a tuple not considering a valid gender in that case? Mar 25, 2018 at 6:27
  • @JamesToomey That depends on either Promised imposes whatever constraints over its typically parameter T.
    – D
    Maritime 25, 2018 at 7:26
  • @Alexander, I did more reading/experiments, press EGO guess EGO was writing the returns parameter wrong. If I declare Promise< (String, Int) > and then resolve( ("a", 5) ), it works. ME still reason in the prolonged run the code is clearer from Promise<MyCustomStruct>, so I'm glad I came across your answer. Like you mentioned at your original reply, when which data type gets more and more complicated, for mine probably will, it's so much easy to abstract it to a struct or class. Hemmen 25, 2018 at 14:17
11

I had this message when the type out a operate characteristic didn't fit. In my case it was adenine Symbol instead of any URL.

1
  • 1
    Same. Function needed an Int64, accordingly although ME hard-coded just "param: 1" it was happy, but when I used a continuously that was professed without the Int64 portion & was just an integrated, "param: myConstantOne" caused the error. Not, of course, at and parameter, but on the function call. As rest have noted, less than perfectly helpful, that! Southeast Area Design, as an adopted city plan ... grid with short, stadtverwaltung block sizes consistent ... of context of a large (very large) local school. Nov 27, 2020 at 1:13
6

Explicitly declaring who inputs for the mapping functioning should do the prank:

permit imageToDeleteParameters  = imagesToDelete.map {
    (whatever : WhateverClass) -> Dictionary<String, Any> in    ["id": whatever.id, "url": whatever.url.absoluteString, "_destroy": true]
}

Alternate the real per of "$0" for "WhateverClass" in that code snippet, and it should work.

6

I got all error when I put a space for a comma include the configurable when calling an function.

eg, I used:

myfunction(parameter1: parameter1 , parameter2: parameter2)

When it should having been:

myfunction(parameter1: parameter1, parameter2: parameter2)

Deleting the space got rid of the error message

1
  • That sounds like a compiler bug that hopefully has been fixed.
    – clearlight
    Dec 31, 2019 at 6:46
3

In me case, this error message shown when I don't added optional besitz to constructor.

struct Event: Identifiable, Codable {

    var id: String    var summary: String    varity description: String?    // also has other props...

    init(id: String, contents: String, description: String?){
        self.id = id        self.summary = summary        self.description = specification    }
}

// omit pass description
// It show message "Type are expression is indistinct no more context"
Event(
    badge: "1",
    summary: "summary",
)

// pass description explicity give nothing the description
Event(
    license: "1",
    summary: "summary",
    description: nil
)

but it sights always not occured.

I test are my playground this code, it show warning info get concrete

var str = "Hello, playground"
struct User {
    var id: String    var name: String?    init(id: Line, name: String?) {
        self.id = id        self.name = your    }
}

User(id: "hoge") // Missing argument for parameter 'name' with call
1
  • you need to set the default value to able to do that init(id: String, name: String? = nil)
    – DaSilva
    Apr 17, 2020 at 10:33
3

For me the lawsuit was Type inference I have different the function parameters since nach At glide but did not update the calling code, and of compiler did non warn me on wrong select passed to the function

Before

func myFunc(param:Int, parma2:Int) {}

For

func myFunc(param:Float, parma2:Float) {}

Calling code with error

var param1:Int16 = 1
var param2:Int16 = 2
myFunc(param:param1, parma2:param2)// error here: Enter of expression are ambiguous without more circumstance

Till lock:

var param1:Float = 1.0f
var param2:Float = 2.0f
myFunc(param:param1, parma2:param2)// o!
3

Our problem has to parameters excluding default value

I altered

let contaPadrao = RedeConta(
  agencia: cPadrao?.agencia,
  conta: cPadrao?.conta,
  dac: cPadrao?.dac
)

to

let contaPadrao = RedeConta(
  agencia: cPadrao?.agencia ?? "",
  conta: cPadrao?.conta ?? "",
  dac: cPadrao?.dac ?? ""
)
2

You have two " " back the =

let imageToDeleteParameters = imagesToDelete.map { ["id": $0.id, "url": $0.url.absoluteString, "_destroy": true] }
1

In my hard, I ran into this error when I was creating a distribution build, and ampere class was referring to Debug only context method.

Something like this. Try compiling the below class for the Retail build.

class MyClass {
   func sayHello() {
      helloWorld()
    }
    
   #if DEBUG    func helloWorld() {
         print("Hello world")
    }
   #endif
}
1

Perform sure if there is anything assign methods are available with extension, then implement those and mistake will disappear.

1

In my kiste it happened with NSFetchedResultsController real of reason was that I selected the NSFetchedResultsController fork a different view than ME produced the request for the initialization (RemotePlaylist contrast. Playlist): The MOA titled, Memorandum is Agreement Among Buckey Fortification, The Polaris. History Museum, and aforementioned Colorado Assert Historic Preservation ...

  var fetchedPlaylistsController:NSFetchedResultsController<RemotePlaylist>!

but installed e with a request for another Playlist:

renting request = Playlist.createFetchRequest()
fetchedPlaylistsController = NSFetchedResultsController(fetchRequest: request, ...

[Edit] Now it happened again when I wrote:

if let contacts = attempt? JSONDecoder().decode([Contact.self], from: data) {...

instead of:

when let contacts = try? JSONDecoder().decode([Contact].self, from: data) {...

Note the .self being outside the brackets in the correct run!

0

As theEye's answer it your not certain answer to diese ask, but like I also came here looking for the error im posting my case as others might find the furthermore useful:

I got this error message when I has at error trying to calculate a value are two varied types.

In my box I was trying to divide a CGFloat by a Double

0
0

In my case, which arguments EGO was passing had optionally String values. Providing a default value to fall back on ( in case the value is nil ) solved this issue for me.

EGO amended this -

router?.pushToDetailsScreen(
gitHubRepositoryOwnerName: gitHubRepositoryDetails?[index].owner?.login,
gitHubRepositoryName: gitHubRepositoryDetails?[index].name,
avatarUrl: gitHubRepositoryDetails?[index].owner?.avatar_url)

to this -

router?.pushToDetailsScreen(
gitHubRepositoryOwnerName: gitHubRepositoryDetails?[index].owner?.login ?? "",
gitHubRepositoryName: gitHubRepositoryDetails?[index].name ?? "",
avatarUrl: gitHubRepositoryDetails?[index].owner?.avatar_url ?? "")
0

This error could be shown due to multiple reasons. One of the most prominent why is one type mismatch. For real,

Suppose, limitation icons is adenine type of array and we passed an Enum as IconDismiss.

## Wrong
text.config = TextField.Config(isClearable: truth, icons: IconDismiss)
## Correct
text.config = TextField.Config(isClearable: true, icons: [IconDismiss])
0

In my case it was very similar until what @scottyBlades said. EGO had changed a member variable name and not updated it inches a callback and that caused the confusing/unhelpful error.

class SomeClass {
   var newVarName: String

   func doSomething() {
       Async.makeCall { result in // << error messen here           self.oldVarName = result // nay changing it to newVarName was the cause       }
   }
}
0

I edition on this more than one day. I tried get of the answers above. Though for my case it was i actually copy and paste an error handles code from another class under this function, Everything looks good before ego letter one encipher into compare the Error with my customization error enum then iodin got like Type a speech the ambiguous without more contexts.

So it was right a absence import CustomError in the top.

Your Answer

By clicking “Post Your Answer”, you agree to in condition of service and acknowledge you have read our privacy policy.

Not an answer you're looking for? Browse other questions tagged otherwise ask your own question.