簡體   English   中英

Swift 中的文字字符串與“字符串”

[英]Literal String vs. `String` in swift

與 swift 一起玩我發現這令人驚訝:

"123".integerValue // <= returns 123

var x = "123"
x.integerValue     // <= Error: String does not have a member named integerValue

有人可以解釋一下嗎?

我的猜測是,在第一個示例中,編譯器使用對integerValue的調用作為推斷類型的附加信息(在 NSString 和 Swift String 之間進行選擇)。

在第二個示例中,它可能默認為 Swift 字符串,因為它不計算多行。

我相信這是類型推斷在起作用的一個例子。 當你這樣做時: "123".integerValue編譯器檢測到在這種情況下你想使用NSString (當你使用字符串文字作為目標 c 函數的參數時,它也"123".integerValue

一個類似的例子是:

// x is an Int
let x = 12

// here we tell the compiler that y is a Double explicitly
let y: Double  = 12

// z is a Double because 2.5 is a literal Double and so "12" is also
// parsed as a literal Double
let z = 12 * 2.5

使用.toInt()

var x = "123"

var num: Int = x.toInt()

如果你這樣做:

var x = "123" as NSString
x.integerValue

var x : NSString = "123" // or this as Sulthan suggests

它不會顯示那個錯誤。

我認為你的第一個例子是自動選擇你想要使用 NSString 因為 NSString 只有這個 .integerValue 調用。

第二個示例可能失敗了,因為它沒有被告知它是什么,而是決定使用 swift 字符串。

暫無
暫無

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

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