调用一个Objective-C方法时,Swift的NilLiteralConversion错误

时间:2014-10-29 02:24:57

标签: objective-c swift

我试图从Swift中调用一个Objective-C方法,但是,有一个错误,我不知道如何解决。

self.clisitef.IniciaFuncaoSiTefInterativo(modalidade, pValor: self.amount, pNumeroCupomFiscal: numeroCupom, pDataFiscal: dateFormated, pHorario: timeFormated, pOperador: self.userOperator, pRestricoes: nil)

最后一个论点" pRestricoes"不接受零。它会触发错误

Cannot convert expressions type... NilLiteralConversion

看到Objective-C中的方法,我无法理解错误:

IniciaFuncaoSiTefInterativo (int Modalidade, char *pValor,
                                                     char *pNumeroCuponFiscal,
                                                     char *pDataFiscal, char *pHorario,
                                                     char *pOperador, char *pRestricoes);
你能帮助我吗?非常感谢!

在Objetive-C中使用所有正确的参数进行相同的调用:

[_clisitef IniciaFuncaoSiTefInterativo: Modalidade pValor:@"1000"
 pNumeroCupomFiscal:_trnCupom pDataFiscal:_trnData
 pHorario:_trnHora pOperador:@"Teste" pRestricoes:nil];

1 个答案:

答案 0 :(得分:1)

该错误消息极具误导性 - nil是您通话中唯一正确的参数!该方法映射到Swift,如下所示:

IniciaFuncaoSiTefInterativo(Modalidade: Int32, pValor: UnsafeMutablePointer<Int8>,
    pNumeroCuponFiscal: UnsafeMutablePointer<Int8>, pDataFiscal: UnsafeMutablePointer<Int8>,
    pHorario: UnsafeMutablePointer<Int8>, pOperador: UnsafeMutablePointer<Int8>,
    pRestricoes: UnsafeMutablePointer<Int8>)

您需要确保您发送的第一个参数是Int32,这很简单:

self.clisitef.IniciaFuncaoSiTefInterativo(Int32(modalidade), ...)

但其余的比较棘手,因为没有一种非常简单的方法可以从Swift UnsafeMutablePointer<Int8>中获取String(我假设你的其他参数是什么)。但是,您可以在需要T的地方传递UnsafeMutablePointer<T>数组,因此我们将字符串转换为[Int8]。使用一个功能来隐藏gobbledegook,你的通话也不会太糟糕:

func toCharArray(string: String) -> [Int8] {
    return string.withCString { cString in
        var chars: [Int8] = []
        var i = 0
        do {
            chars.append(cString[i])
        } while cString[i++] != 0
        return chars
    }
}

self.clisitef.IniciaFuncaoSiTefInterativo(Int32(modalidade), 
    pValor: toCharArray(self.amount),
    pNumeroCupomFiscal: toCharArray(numeroCupom),
    pDataFiscal: toCharArray(dateFormated),
    pHorario: toCharArray(timeFormated),
    pOperador: toCharArray(self.userOperator),
    pRestricoes: nil)