簡體   English   中英

無法分配類型為'String'的值? 輸入“ Int”

[英]Cannot assign value of type 'String?' to type 'Int'

我收到錯誤消息無法分配類型為'String'的值? 輸入“ Int”

我已經瀏覽了其他類似問題,但仍然顯示錯誤。

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

     //Some sort of message such as Progress hud
 }

提前致謝!

我有您的問題,實際上Swift在這里發生的是類型安全的語言

因此,您要做的是將一個String值存儲在Int ,這不會自動發生,您需要將其轉換為Int

像這樣Int(sunscreenName.text)

但是有一個問題,並不是所有的字符串都可以轉換為Int類型,例如

let name = "roshan"

如果您嘗試將其轉換為Int ,它將給您零

let a = Int(name)

所以最好在這里由Swift提供一個可選的Binding

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

我建議您通讀《 Swift編程語言》以更好地理解Swift及其基本概念,因為這個問題是相當基本的。

您犯了幾個錯誤:

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

錯了 在Swift中,如果您打算以后使用該值,則應使用if let而不是與nil進行比較。 nil比較,這些值是可選的,但是if let它們解開,則將它們取消包裝。 因此,改為這樣做:

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

現在,您有了sunscreenTextreapplyText變量,它們的類型為String ,而不是String? (即它們不是可選的)。

現在,有這兩行。

sunscreen = sunscreenName.text!
reApplyTime = reapplyTime.text

您沒有說出是誰在發出錯誤,但是在兩種情況下,問題都是相同的。 首先,使用展開后的sunscreenTextreapplyText變量代替sunscreenName.text! reapplyTime.text 接下來,如果其中之一是Int而不是String ,則將其強制轉換。 Swift與JavaScript不一樣,它不會自動將值從一種類型轉換為另一種類型,因此,如果某物是字符串並且我們需要一個整數,則必須自己將其轉換。

(假設reapplyTime是給出錯誤的行:)

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

我們必須解包的原因是,如果字符串不能被轉換為整數,則Int(String)可以返回nil 或者,我們可以提供一個默認值:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM