Home > Back-end >  Extra trailing closure passed in call error while using DynamoDB with Swift
Extra trailing closure passed in call error while using DynamoDB with Swift

Time:07-15

I was trying to use DynamoDB with swift for a MacOS application. The problem is that, even when copying the function suggested by the AWS documentation (https://docs.aws.amazon.com/sdk-for-swift/latest/developer-guide/examples-ddb-items.html), I am getting the error:

Extra trailing closure passed in call

Example function:

func getDynamoDbItem(dynamoDbClient: DynamoDbClient,
                     nameOfTable: String,
                     keyName: String,
                     keyVal: String) {
    let keyToGet = [keyName : DynamoDbClientTypes.AttributeValue.s(keyVal)]
    dynamoDbClient.getItem(input: GetItemInput(key: keyToGet, tableName: nameOfTable)) { result in
        switch(result) {
        case .success(let response):
            guard let numbersMap = response.item else {
                return
            }
            for returnedKey in numbersMap {
                print("\(returnedKey.key) : \(returnedKey.value)")
            }
        case .failure(let err):
            print(err)
        }
    }
}

Is there something I am missing?

CodePudding user response:

The documentation on the provided link is outdated. The newer version of the dependency is already using async requests.

func getDynamoDbItem(dynamoDbClient: DynamoDbClient,
                     nameOfTable: String,
                     keyName: String,
                     keyVal: String) async {
    do {
        
        let keyToGet = [keyName : DynamoDbClientTypes.AttributeValue.s(keyVal)]
        let result = try await dynamoDbClient.getItem(input: GetItemInput(key: keyToGet, tableName: nameOfTable))
        
        // use result
        
    } catch {
        // handle error
    }
    
}

Edit:

private var dynamoDBResponseSubject = PassthroughSubject<GetItemOutputResponse, Error>()
var dynamoDBResponse: AnyPublisher<GetItemOutputResponse, Error> { dynamoDBResponseSubject.eraseToAnyPublisher() }


override func viewDidLoad() {
    super.viewDidLoad()
    Task {
        getDynamoDbItem(dynamoDbClient: dynamoDbClient, nameOfTable: "nameOfTable", keyName: "keyName", keyVal: "keyVal")
    }
}


func getDynamoDbItem(dynamoDbClient: DynamoDbClient,
                     nameOfTable: String,
                     keyName: String,
                     keyVal: String) {
        do {
            
            let keyToGet = [keyName : DynamoDbClientTypes.AttributeValue.s(keyVal)]
            let result = try await dynamoDbClient.getItem(input: GetItemInput(key: keyToGet, tableName: nameOfTable))
            dynamoDBResponseSubject.send(result)                
        } catch {
            // handle error
        }
}

Or you can remove the async from the getDynamoDbItem... method and add the do { ... } catch { ... } block within a Task

  • Related