programing

더 많은 컨텍스트 Swift가 없으면 표현 유형이 모호합니다.

instargram 2023. 4. 12. 21:44
반응형

더 많은 컨텍스트 Swift가 없으면 표현 유형이 모호합니다.

최신 Swift 버전으로 업그레이드하려는 프로젝트에서 코드의 이 부분에 대해 "Type of expression is more contexts"라는 문구를 받았습니다.난 그걸 이해할 수 없을 것 같아.여러 가지를 시도해 봤지만 잘 되지 않아요.

이 행의 구문에 문제가 있습니다.

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

풀코드:

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 }
        ]
    }
}

이는 잘못된 인수 이름을 가진 함수가 있을 때 발생합니다.

예:

functionWithArguments(argumentNameWrong: , argumentName2: )

그리고 당신은 당신의 기능을 다음과 같이 선언했습니다.

functionWithArguments(argumentName1: , argumentName2: ){}

이 문제는 일반적으로 변수 이름을 변경할 때 발생합니다.그럴 때는 꼭 리팩터링 하세요.

이 문제는 선택한 메서드 또는 속성의 일부가 잘못된 유형의 속성 또는 메서드에 액세스하려고 할 때 발생할 수 있습니다.

트러블 슈팅 체크리스트를 다음에 나타냅니다.

  • 콜 사이트와 구현에서 일치하는 인수 유형.
  • 인수명은 콜 사이트와 구현에서 일치합니다.
  • 메서드명은 콜사이트와 구현에서 일치합니다.
  • 및 "사용 및 구현에 일치합니다.enumerated())
  • 프로토콜이나 제네릭과 같이 모호한 유형의 중복된 방법이 없습니다.
  • 컴파일러는 유형 추론을 사용할 때 올바른 유형을 추론할 수 있습니다.

전략

  • 방법을 보다 간단한 방법/실현으로 분할해 보십시오.

를 들어, 예를 들어, '하다', '실행하다', '실행하다', '실행하다'라고.compactMap커스텀 타입의 배열에 있습니다.에는 '이렇게 하다'로 됩니다.compactMap메서드를 사용하여 다른 사용자 지정 구조를 초기화하고 반환합니다.이 에러가 발생하면, 코드의 어느 부분이 문제인지 구별하기 어렵습니다.

  • 「」를 할 수 .for in compactMap.
  • 인수를 직접 전달하는 대신 for 루프의 상수에 할당할 수 있습니다.

이 시점에서, 할당하고 싶다고 생각한 재산이 실제로 건네고 싶은 가치를 가지는 재산이 아닌, 깨달음을 얻을 수 있습니다.

이 질문에 대한 답변은 아니지만, 오류를 찾기 위해 여기에 왔기 때문에 다른 사람들도 도움이 될 수 있습니다.

이 Swift 하였습니다.Swift 를 에러가 하였습니다.for (index, object)「」를 하지 않고, ..enumerated()★★★★★★★★★★★…

사전이 균질하지 않기 때문에 컴파일러는 어떤 종류의 사전을 만들어야 할지 알 수 없습니다.하다을 「이렇게 하는 것」으로 입니다.[String: Any]모든 게 엉망진창이 될 거야

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 }
] as [String: Any]

이건 구조물을 위한 일이야이 데이터 구조를 사용하여 작업을 대폭 간소화할 수 있습니다.

함수 파라미터의 유형이 맞지 않을 때 이 메시지를 받았습니다.제 경우 URL이 아닌 String이었습니다.

해당 매핑 함수의 입력을 명시적으로 선언하면 다음과 같은 작업이 수행됩니다.

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

이 코드 스니펫의 "WhatyClass" 대신 "$0"의 실제 클래스를 대체하면 작동합니다.

함수를 호출할 때 매개 변수에서 쉼표 앞에 공백을 넣었을 때 이 오류가 발생했습니다.

예:

myfunction(parameter1: parameter1 , parameter2: parameter2)

그러나 다음과 같이 해야 합니다.

myfunction(parameter1: parameter1, parameter2: parameter2)

공간을 삭제하면 오류 메시지가 제거되었습니다.

제 경우, 이 오류 메시지는 생성자에 옵션 속성을 추가하지 않을 때 표시됩니다.

struct Event: Identifiable, Codable {

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

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

// skip pass description
// It show message "Type of expression is ambiguous without more context"
Event(
    id: "1",
    summary: "summary",
)

// pass description explicity pass nil to description
Event(
    id: "1",
    summary: "summary",
    description: nil
)

항상 그런 일은 일어나지 않는 것 같아요.

내 놀이터에서 이 코드를 테스트하면, 더 구체적인 것에 대한 경고를 보여줍니다.

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

User(id: "hoge") // Missing argument for parameter 'name' in call

내게는 타입 추론이라고 할 수 있다.나는 함수 파라미터를 int To float에서 변경했지만 호출 코드를 업데이트하지 않았다.그리고 컴파일러는 함수에 전달된 잘못된 타입에 대해 경고하지 않았다.

전에

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

끝나고

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

오류가 있는 발신 코드

var param1:Int16 = 1
var param2:Int16 = 2
myFunc(param:param1, parma2:param2)// error here: Type of expression is ambiguous without more context

수정 방법:

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

문제는 디폴트값이 없는 파라미터입니다.

나는 변했다

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

로.

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

두 개가 요." "before =

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

이 문제는 NSFetchedResultsController에서 발생했으며, 그 이유는 초기화 요청을 작성한 모델과 다른 모델에 대해 NSFetchedResultsController를 정의했기 때문입니다(RemotePlaylist vs.재생 목록:

  var fetchedPlaylistsController:NSFetchedResultsController<RemotePlaylist>!

다른 재생목록에 대한 요구로 시작했습니다.

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

이 경우 디스트리뷰션빌드를 작성할 때 이 오류가 발생했는데 클래스에서 Debug only context 메서드를 참조하고 있었습니다.

이런 거.배포 빌드에 대해 아래 클래스를 컴파일해 보십시오.

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

확장에서 사용할 수 있는 위임 메서드가 있는지 확인한 후 해당 메서드를 구현하면 오류가 사라집니다.

에는 제가 인 optional, 가, 가, i, 내, i, in, in, in, in, in, in, in, in, in, in, in, in, in, in, in, in,String가치.폴백할 기본값 제공(값이 다음과 같은 경우)nil)에서 이 문제를 해결했습니다.

내가 이걸 바꿨어-

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

여기에 대해서-

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

이 오류는 여러 가지 이유로 표시될 수 있습니다.가장 중요한 이유 중 하나는 타입 불일치입니다.예를들면,

파라미터 아이콘이 배열의 일종이고 Enum을 IconDismiss로 전달했다고 가정합니다.

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

제 경우 @scotyBlades가 말한 것과 매우 유사합니다.멤버 변수명을 변경하고 콜백으로 갱신하지 않아 혼란스럽고 도움이 되지 않는 에러가 발생했습니다.

class SomeClass {
   var newVarName: String

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

The Eye의 답변은 이 질문에 대한 답변이 아닙니다.또, 이 에러를 찾아 여기에 왔기 때문에, 다른 사람에게도 도움이 될 수 있는 제 케이스를 투고하고 있습니다.

두 가지 다른 유형의 값을 계산하려고 할 때 이 오류 메시지가 나타납니다.

내 경우엔, 난 이 둘을 나누려고 했었어CGFloat에 의해Double

언급URL : https://stackoverflow.com/questions/40894582/type-of-expression-is-ambiguous-without-more-context-swift

반응형