Swift可选参数未解包

时间:2016-10-27 16:49:48

标签: swift swift3

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

var entries = [String]()

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

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

2 个答案:

答案 0 :(得分:4)

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

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
    }
}

答案 1 :(得分:0)

即使您检查了nil,您仍然没有将Int?转换为Int以用作索引。为此,您需要打开Optional

var entries = [String]()

func addEntry(text: String, position: Int?) {
  // guard against a nil position by attempting to
  // unwrap it with optional binding
  guard
    // test for nil and unwrap using optional binding
    let unwrappedPosition = position,
    // make sure the position isn't 
    // past the end of the array
    unwrappedPosition < entries.count else {
      // can't unwrap it or 
      // it's out of bounds,
      // append it
      entries.append(text)
      return
  }

  // successfully unwrapped, set item at index
  entries[unwrappedPosition] = text
}