たとえば、コマンドを実行するCommander
オブジェクトがあります。戻り値の型は常に同じではなく、コマンドに応じて変化します。指定された汎用関数パラメータへのキャスト
コマンドをコマンダーに転送し、その結果が特定の型(パラメータとして渡されたもの)かどうかをテストし、キャストが成功した場合に成功クロージャを呼び出す前にテストし、それ以外の場合は失敗の終了となります。
私はこのようなもので、一般的なパラメータを使用して試してみた:それをそのよう
self.postCommand("command", expectedResponseType: [String: AnyObject], success: { (content: [String: AnyObject]) in
print("Success")
}) { (error: NSError?) in
print("Failure")
}
を呼び出す
func postCommand<T>(command: String, expectedResponseType: T, success: T -> Void, failure: (NSError?) -> Void) {
Commander.execute(command, completion: { (response: AnyObject?) in
guard let content = response as? T else {
failure(nil)
return
}
success(content)
})
}
しかし、私は、コンパイラからエラーを取得する:
Cannot convert value of type '([String : AnyObject]) -> Void' to expected argument type '_ -> Void'
このようなキャストをしようとすると:
guard let content = response as? expectedResponseType
コンパイラはexpectedResponseType
が型ではないと不平を言っています。
私はそれを行う方法を理解できません。それも可能ですか?