Swift 可选参数未解包 [英] Swift optional parameter not unwrapped

查看:42
本文介绍了Swift 可选参数未解包的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有可选参数(位置)的函数.我测试它为零,但 Xcode 仍然向我显示一个错误:可选类型 Int 的值?未解包"并建议我使用!"或?".

I have a function with a optional parameter(position). I test for it to be nil but still Xcode shows me an error: "Value of optional type Int? not unwrapped" and suggests me to use "!" or "?".

var entries = [String]()

func addEntry(text: String, position: Int?) {
    if(position == nil) {
        entries.append(text)
    } else {
        entries[position] = text
    }
}

我是 Swift 的新手,不明白为什么这不行.在这个 if 子句中,编译器应该 100% 确定该位置已定义,或者?

Im new to Swift and don't understand why this isn't ok. Within this if-clause the compiler should be 100% sure that position is defined, or?

推荐答案

有几种方法可以正确编码:

There are a few ways to code this properly:

func addEntry(text: String, position: Int?) {
    // Safely unwrap the value
    if let position = position {
        entries[position] = text
    } else {
        entries.append(text)
    }
}

或:

func addEntry(text: String, position: Int?) {
    if position == nil {
        entries.append(text)
    } else {
        // Force unwrap since you know it isn't nil
        entries[position!] = text
    }
}

这篇关于Swift 可选参数未解包的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆