【问题标题】:in swift assert(0) Cannot convert value of type Int to expected argument type Bool在 swift assert(0) 中无法将 Int 类型的值转换为预期的参数类型 Bool
【发布时间】:2017-05-17 08:38:31
【问题描述】:

我正在将目标 -C 转换为 swift,但是当我在 swift 中编写 assert(0) 时出现错误,错误消息是“在 swift assert(0) 中无法将 Int 类型的值转换为预期的参数类型 Bool”

我在目标 -c 中的代码:

switch ([[UIApplication sharedApplication] applicationState]) {
        case UIApplicationStateActive:
            [statusStr appendString:@"foreground"];
            break;
        case UIApplicationStateInactive:
            [statusStr appendString:@"inactive"];
            break;


        case UIApplicationStateBackground:
            [statusStr appendString:@"background"];
            break;

        default:
            assert(0);
            break;
    }

并迅速翻译:

 switch UIApplication.shared.applicationState {

            case .active:
                statusStr += "foreground"
            case .inactive:
                statusStr += "inactive"
            case .background:
                statusStr += "background"
            default:
                assert(0)
                break

            }

我不知道 Swift 中的 0 意思是 assert(true)assert(false)

提前致谢。

【问题讨论】:

  • 你对错误信息有什么不明白的地方,它已经很清楚了。 assert 需要一个 Bool,你给它一个 Int。那是行不通的。做assert(false),不管该做什么。
  • 试试assert(true)assert(false) ... 哪个会触发?
  • @MartinR assert(false) 将触发
  • 顺便说一句,fatalError() 可能是更好的选择,比较 stackoverflow.com/questions/29149040/…
  • 实际上在 Swift 中根本不需要 default 的情况,因为 switch 是穷举的。你没有收到将永远不会被执行警告吗?

标签: objective-c swift assert


【解决方案1】:

由于OC弱类型语言,它可以自动翻译0为false,所以在assert中可以运行,但是swift是强类型语言,所以你应该使用assert(false)或者你应该自己翻译它

p>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-12
    • 2021-11-23
    • 2020-09-03
    • 2019-05-12
    • 1970-01-01
    相关资源
    最近更新 更多