【问题标题】:Cannot convert value of type '_?' to type '[AFTParty]?' in coercion - Swift无法转换类型“_?”的值输入“[AFTParty]?”强制 - 斯威夫特
【发布时间】:2016-08-11 11:54:12
【问题描述】:

我正在读取一个返回对象数组的 JSON。我想将 JSON 响应绑定到我的对象 AFTParty,我遇到了这个编译错误:

无法转换“_?”类型的值输入“[AFTParty]?”

AFTParty 是一个符合 Decodable 协议的类,我正在使用 Himotoki 来完成这项工作。

我的 JSON:

[
{
id: 1,
partyName: "x",
partyAuthor: [
{
id: 1,
username: "mtfons",
name: "marco",
lastname: "fonseca",
phoneNumber: "91859158",
email: "mt.fonseca23@gmail.com"
}
],
partyDescription: null,
partyStyle: null,
partyPermission: "PUBLICA",
partyLocation: {
id: 1,
latitude: "1248174",
longitude: "1428149"
},
prices: [ ],
partyDetailToJoin: "x",
partyDateBegin: null,
partyDateEnd: null,
partyImagesPath: [ ],
partyParticipants: [
{
id: 1,
username: "x",
name: "x",
lastname: "x",
phoneNumber: "x",
email: "x@gmail.com"
},
{
id: 2,
username: "x",
name: "ajfk",
lastname: "jfa",
phoneNumber: "x",
email: "teste@teste.com"
}
],
time: null,
partyType: null
}
]

给出错误的代码:

      let partyDeserializer = AFTPartyDeserializerImplementation(network: network)
            describe("Response") {
                it("returns party if the network works correctly.") {
                    var response = [AFTParty]()
                    partyDeserializer.getParty().on(next: { response = $0 }).start()

                }
     }


       public func getParty() -> SignalProducer<AFTParty, AFTNetworkError> {
            let url = AFTRouter.Parties.URL
            return network.requestJSON(url, parameters: nil)
                .attemptMap { json in
                    if let response = (try? decodeValue(json)) as [AFTParty]? {
                        return Result(value: response)
                    }
                    else {
                        return Result(error: .IncorrectDataReturned)
                    }
            }
        }

感谢您的帮助,我很抱歉我的英语不好。

【问题讨论】:

  • 我认为问题可能出在as 演员身上。应该是as?

标签: arrays swift alamofire reactive-cocoa


【解决方案1】:

你是说

public func getParty() -> SignalProducer<[AFTParty], AFTNetworkError> {

?

【讨论】:

    【解决方案2】:

    如果decodeValue(json) 返回AnyObject,那么您可能希望使用as? 进行投射,而不是as

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-04-15
      • 2017-07-15
      • 1970-01-01
      • 1970-01-01
      • 2017-07-22
      • 2017-03-24
      • 1970-01-01
      相关资源
      最近更新 更多