Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/swift/17.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何将Objective-C BOOL转换为Swift';s Bool,返回的参数之一为NSError**_Objective C_Swift - Fatal编程技术网

如何将Objective-C BOOL转换为Swift';s Bool,返回的参数之一为NSError**

如何将Objective-C BOOL转换为Swift';s Bool,返回的参数之一为NSError**,objective-c,swift,Objective C,Swift,我有一个项目,我正在尝试使用Swift的新模块。对于其中一个新类,我使用Swift 3.2中Objective-C类的现有方法 以下是该方法的签名 - (BOOL)canLoginWithUsername:(NSString *)username password:(NSString *)password error:(NSError **)error 我尝试在swift中使用这种方法 if try loginLogicHandler.canLogin(withUsername: us

我有一个项目,我正在尝试使用Swift的新模块。对于其中一个新类,我使用Swift 3.2中Objective-C类的现有方法

以下是该方法的签名

- (BOOL)canLoginWithUsername:(NSString *)username password:(NSString *)password error:(NSError **)error
我尝试在swift中使用这种方法

    if try loginLogicHandler.canLogin(withUsername: usernameValue, password: passwordValue) as Bool {

}
但是,我得到一个编译器错误,如下所示

无法在强制中将类型()的值转换为类型“Bool”

我该怎么做才能让它工作


有人能建议如何解决这个问题吗?

通过引用返回
BOOL
和返回
NSError
的Objective-C方法将暴露于Swift,因为这些方法使用
try
/
catch
错误处理机制,并返回
Void
。如果您查看生成的接口,您可能会看到它看起来像这样:

func canLogin(withUsername: String, password: String) throws // notice no return type
如果Objective-C方法失败,它将返回
NO
,并填充错误指针,然后Swift抛出该错误。因此,您需要使用
try
catch

do {
    try loginLogicHandler.canLogin(with: bla, and: bla)

    // if canLogin returned YES, you get here
} catch {
    // if canLogin returned NO, you get here
}
或者,您可以使用
try?
。这个有点奇怪;您将获得可选的
Void
,因此如果方法成功,您将获得
Void
,如果方法失败,您将获得
nil

if (try? loginLogicHandler.canLogin(with: bla, and: bla)) != nil {
    // the method returned YES
}

通过引用返回
BOOL
和返回
NSError
的Objective-C方法作为使用
try
/
catch
错误处理机制和返回
Void
的方法公开给Swift。如果您查看生成的接口,您可能会看到它看起来像这样:

func canLogin(withUsername: String, password: String) throws // notice no return type
如果Objective-C方法失败,它将返回
NO
,并填充错误指针,然后Swift抛出该错误。因此,您需要使用
try
catch

do {
    try loginLogicHandler.canLogin(with: bla, and: bla)

    // if canLogin returned YES, you get here
} catch {
    // if canLogin returned NO, you get here
}
或者,您可以使用
try?
。这个有点奇怪;您将获得可选的
Void
,因此如果方法成功,您将获得
Void
,如果方法失败,您将获得
nil

if (try? loginLogicHandler.canLogin(with: bla, and: bla)) != nil {
    // the method returned YES
}

查看此链接可能会有所帮助:比较查看此链接可能会有所帮助:比较谢谢@Charles!谢谢你,查尔斯!