0

Im trying to make a calculator in Swift but I have a problem I have put everything in a array and want to find the index of the X and /

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

The array looks as it should and this finds the index but it write it out as: ex.

[1,x,5,+,4]

willBeCountArray.index(of: "x") is printed as Optional(1) `

--> I want to compare x and / index to start from the left. But it wont go in this format

WHAT DO I DO?

biigem
  • 11
  • Step 1: Search Stack Overflow! [Printing optional variable](https://stackoverflow.com/questions/25846561/printing-optional-variable) –  Mar 26 '20 at 02:16
  • `if let idx = willBeCountArray.index(of: "x") { print("found at index \(idx)") } else { print("not found") }` – vacawama Mar 26 '20 at 02:18

1 Answers1

0

Array.index(of:) is deprecated. You should use Array.firstIndex(of:)

Array.firstIndex(of:) returns an optional Int Int?. Meaning it returns nil if the entry is not found. (a non-optional Int can never be nil and is a different type in Swift.

Optional Int's have to be unwrapped to Int before comparison.

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.
}
nine stones
  • 3,264
  • 1
  • 24
  • 36