【问题标题】:Int to int in SwiftSwift 中的 int 到 int
【发布时间】:2020-03-26 10:37:54
【问题描述】:

我正在尝试用 Swift 制作一个计算器,但我遇到了问题 我已将所有内容都放在一个数组中,并希望找到 X 和 /

的索引

willBeCountArray.index(of: "x") willBeCountArray.index(of: "/")

数组看起来像它应该的那样,它找到了索引,但它把它写成: 例如。

[1,x,5,+,4]

willBeCountArray.index(of: "x") 打印为 可选(1)`

--> 我想比较x和/index从左边开始。但它不会采用这种格式

我该怎么办?

【问题讨论】:

  • 第 1 步:搜索 Stack Overflow! Printing optional variable
  • if let idx = willBeCountArray.index(of: "x") { print("found at index \(idx)") } else { print("not found") }

标签: swift xcode int optional


【解决方案1】:

Array.index(of:) 已弃用。你应该使用 Array.firstIndex(of:)

Array.firstIndex(of:) 返回一个可选的 Int Int?。这意味着如果找不到条目,​​它会返回 nil。 (非可选的 Int 永远不能为 nil,并且在 Swift 中是不同的类型。

在比较之前必须将可选的 Int 解包为 Int。

let optionalIdx = array.firstIndex(of: "x")  // Int? can be nil

// Force unwrap.
// Don't do this as it disables compile time checks and can crash at runtime.
let idx = optionalIdx!   // Int cannot be nil. 

// if let unwrap
if let idx = optionalIdx, 
  let otherIdx = array.firstIndex(of: "/") 
{
  // here both idx and otherIdx are found and not nil.
  // You should be able to compare / work with them here.
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-09-01
    • 1970-01-01
    • 2014-07-26
    • 1970-01-01
    • 2014-12-07
    相关资源
    最近更新 更多