简体   繁体   中英

Cannot assign value of type 'String?' to type 'Int'

I am getting the error message Cannot assign value of type 'String?' to type 'Int'

I have browsed through other questions like this but it still shows the error.

 if sunscreenName.text != nil && reapplyTime.text != nil {
     sunscreen = sunscreenName.text!
     reApplyTime = reapplyTime.text

     //Some sort of message such as Progress hud
 }

Thanks in advance!

I got your problem, actually what happens here Swift is is type safe langauge

So what you are doing is is to store a String value in Int which will not happen automatically you need to convert it to Int

like this Int(sunscreenName.text)

But there is a catch there not all string are convertible to Int type, fo eg

let name = "roshan"

if you try to convert it to Int it will give you a nil

let a = Int(name)

So its better you do a optional Binding here provided by Swift

if let sunValue = Int(sunscreenName.text),let reApplyValue = Int(reapplyTime.text) {
 sunscreen = sunValue
 reApplyTime = reApplyValue
}

I recommend reading through The Swift Programming Language to get a better understanding of Swift and its fundamental concepts, since this question is fairly basic.

You make several mistakes:

if sunscreenName.text != nil && reapplyTime.text != nil {

This is wrong. In Swift, if you plan to use the value later, you should use if let rather than comparing to nil . Comparing to nil leaves the values optional, but if let unwraps them. So, do this instead:

if let sunscreenText = sunscreenName.text, let reapplyText = reapplyTime.text {

Now you have the sunscreenText and reapplyText variables, which are typed String , not String? (ie they are not optional).

Now, there's these two lines.

sunscreen = sunscreenName.text!
reApplyTime = reapplyTime.text

You don't say which one is giving the error, but the issue is the same in either case. First, use our unwrapped sunscreenText and reapplyText variables instead of sunscreenName.text! and reapplyTime.text . Next, if one of these is meant to be an Int instead of a String , cast it. Swift is not like JavaScript, in that it won't automatically convert values from one type to another, so if something is a string and we need an integer, we have to convert it ourselves.

(assuming reapplyTime was the line that was giving the error:)

if let reapplyInt = Int(reapplyText) {
    reapplyTime = reapplyInt
}

The reason we have to unwrap is because Int(String) can return nil if the string is something that can't be converted to an integer. Alternately, we could just provide a default value:

reapplyTime = Int(reapplyText) ?? 0 // sets to 0 if it can't parse the string as an integer

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