You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

求助:Cannot assign value of type 'String?' to type 'Int'报错未解决

解决 "Cannot assign value of type 'String?' to type 'Int'" 错误

Hey there! Let's break down what's causing this error and fix it right away.

错误根源

This error happens because your reApplyTime variable is an Int type, but you're trying to assign reapplyTime.text directly to it. reapplyTime.text is an optional string (String?), and Swift doesn't let you automatically convert between these types—you need to explicitly turn the string into an integer first.

你的代码问题

In your current code, you check that both text fields have values, but you still assign the raw optional string to reApplyTime (which expects an integer):

if sunscreenName.text != nil && reapplyTime.text != nil { 
    sunscreen = sunscreenName.text! 
    reApplyTime = reapplyTime.text // 这里直接把String?类型赋值给了Int变量,导致类型不匹配
    //Some sort of message such as Progress hud 
} 

修复方案

The safest way to handle this is to not only unwrap the text field values but also convert the time string to an integer, while accounting for cases where the input isn't a valid number. Here's the improved code:

// 同时解包文本内容,并尝试将时间字符串转换为Int
if let sunscreenText = sunscreenName.text, 
   let reapplyTimeText = reapplyTime.text, 
   let reapplyTimeInt = Int(reapplyTimeText) {
    sunscreen = sunscreenText
    reApplyTime = reapplyTimeInt
    // 在这里显示你的Progress HUD
} else {
    // 处理输入无效的情况:比如文本为空,或者时间不是有效数字
    // 可以给用户弹出提示,比如"请输入有效的重新涂抹时间(数字格式)"
}

为什么这个方案更可靠?

  • It uses optional binding to safely unwrap text field values (no risky force unwraps with ! that can crash your app).
  • Int(reapplyTimeText) converts the string to an integer—this returns an optional Int?, which only unwraps if the string is a valid number.
  • The else block lets you handle invalid input gracefully instead of letting the app crash or silently fail.

If you're 100% sure that reapplyTime.text will always be a valid number (not recommended for user input, since users can type anything), you could use force unwraps—but this is risky:

if sunscreenName.text != nil && reapplyTime.text != nil { 
    sunscreen = sunscreenName.text! 
    // 强制转换并解包,但若输入非数字会直接崩溃
    reApplyTime = Int(reapplyTime.text!)! 
    // Progress hud code
}

Stick with the first approach for user-facing input—it makes your app way more robust!

内容的提问来源于stack exchange,提问作者Nol4635

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 09:55:31