2014-11-25 38 views
1

我有一個愚蠢的問題,我很肯定,我做錯了什麼,但無法弄清楚它是什麼。我有簡單的遊樂場裏我與斯威夫特運營商玩,來到的情況下,在那裏我有下面的代碼:Swift operators == vs ===

1 != 1 // false 
1 !== "1".toInt() //false 
1 === 1 // true 
1 == "1".toInt() // true 

這應該是完全正常的,但操場編譯器顯示以下錯誤: enter image description here

什麼我做錯了嗎?這個問題究竟意味着什麼?


更新

當我刪除線#2,錯誤消失: enter image description here 的Xcode 6.1版(6A1052d)


更新2

當我比較1 === 1.toInt()我得到另一個錯誤: enter image description here

+0

'!=='和''===是運營商的身份,爲1視爲一個對象*迅速*? – Maroun 2014-11-25 07:48:34

+0

我不這麼認爲。但是讓我困惑的是,那張圖中的第3行很好,但第1行是錯誤的。當我從操場刪除''1!==「1」.toInt()'''時,一切工作正常。我沒有看到區別。可能我有愚蠢的做法,因爲我是Ruby開發者... – 2014-11-25 07:52:44

+0

我更新了描述以避免這些類型的問題 – 2014-11-25 07:55:29

回答

4

===是身份的運營商,只能應用於實例, 它被聲明爲現在

func ===(lhs: AnyObject?, rhs: AnyObject?) -> Bool 

1 === 1作品,因爲編譯器在這裏會自動創建NSNumber實例 。 NSNumber符合IntegerLiteralConvertible 協議:

extension NSNumber : FloatLiteralConvertible, IntegerLiteralConvertible, BooleanLiteralConvertible { 

    /// Create an instance initialized to `value`. 
    required convenience init(integerLiteral value: Int) 

    /// Create an instance initialized to `value`. 
    required convenience init(floatLiteral value: Double) 

    /// Create an instance initialized to `value`. 
    required convenience init(booleanLiteral value: Bool) 
} 

這也可以從與

xcrun -sdk macosx swiftc -emit-assembly main.swift 

生成的彙編代碼看出其示出的

callq __TFE10FoundationCSo8NSNumberCfMS0_FT14integerLiteralSi_S0_ 

兩個呼叫和demangling此函數名與

xcrun swift-demangle __TFE10FoundationCSo8NSNumberCfMS0_FT14integerLiteralSi_S0_ 

給出

ext.Foundation.ObjectiveC.NSNumber.init (ObjectiveC.NSNumber.Type)(integerLiteral : Swift.Int) -> ObjectiveC.NSNumber 

所以在NSNumber1 === 1兩個實例進行比較(這是對象)。

請注意,只有在包含Foundation框架的情況下,這纔有效(即,NSNumber 可用)。否則1 === 1失敗

type 'AnyObject?' does not conform to protocol 'IntegerLiteralConvertible' 

兩個

1 !== "1".toInt() // value of optional type 'Int?' not unwrapped 
1 !== "1".toInt()! // type 'AnyObject?' does not conform to protocol 'IntegerLiteralConvertible' 

編譯沒有編譯,因爲右邊是不是一個對象,而不是字面是 編譯器中的一個對象自動轉換。出於同樣的原因,

let i = 1 
1 !== i // type 'Int' does not conform to protocol 'AnyObject' 

不編譯。


==,在另一方面,是相等運算內容其 操作數進行比較。它是爲自選定義如果基礎類型是equatable:

func ==<T : Equatable>(lhs: T?, rhs: T?) -> Bool 

因此在1 == "1".toInt(),在LHS被轉換爲Int?,然後進行比較 與RHS。

+0

謝謝你的解釋!這非常有意義。 – 2014-11-25 08:18:50

0

Mind you, I never programmed or even heard of Swift, but from the documentation I found and the experience in C#, I try to give an answer I think is correct. If not, I'll remove the answer.

斯威夫特似乎已經(如C#)「optional types」,即標註問號之後的類型標識符,這樣的:int?toInt()似乎是return an "optional int",這與int不一致(如錯誤所示)。

爲了讓這個可選的INT「正常」 INT,使用感嘆號:

1 == "1".toInt()! 
0

了「===」操作符是測試兩個對象的引用是否都指向同一個對象實例

在其他語言中,我知道這是用於測試是否是同樣的類型和值。

但是,當代碼需要整數字面量時,您在字符串文字上調用了to.Int()函數。

我願意這樣做:

let a =「1」; 令B = a.toInt()

如果1!== B {//動作}