简体   繁体   中英

Cannot use optional chaining on non-optional value of type '[Int]'

I am trying to make my code print "Hello World" in Swift 4 by selecting just one of the three numbers in the array and I get the error listed in the title.

func newFunc() {
    let employees = [1, 2, 3]?
    if employees == [1] {
        let printthis = "Hello World!"
        print(printthis)
    } else {
        print("Nothing here")
    }
}

newFunc()

You cannot apply "?" Optional to the object/instance. you can define an object as an Optional by putting the "?" on the type:

let employees: [Int]? = [1, 2, 3]

you employees array will be now an array of Optional Int. It seems that you don't need an optional so you can skip "?" from the defining

And for checking if an array contains a value you can check it by:

if employees.contains(1) {
  let printthis = "Hello World!"
      print(printthis)
} else {
    print("Nothing here")
}

the problem is here

let employees = [1, 2, 3]?

should be like this , you can't append ? for that declaration

let employees = [1, 2, 3]

The code

let employees = [1, 2, 3]?

Is not valid Swift.

If you want to create an optional Array of Ints, use

let employees: [Int]? = [1, 2, 3]

However, it's unlikely that you want an optional let constant. It's probably better to just get rid of the question mark:

let employees = [1, 2, 3]

If you really want employees to be an optional array, and you really want to put the optional specifier on the right-hand side of the declaration, you could do it like this:

let employees = Optional([1, 2, 3])

But again I'm not sure why you'd want an optional let constant as an instance var.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM