[英]Comparing String Objects in Swift
Everyone knows you can use the == Operator to compare things. 每个人都知道您可以使用==运算符进行比较。
if (stringValue1 == stringValue2)
If you do this in Objective-C the program will check if these objects are the same not if both strings do contain the same text. 如果在Objective-C中执行此操作,则程序将检查这些对象是否相同,如果两个字符串确实包含相同的文本,则它们将不同。 If you want to compare the text values you need to use a compare-Method.
如果要比较文本值,则需要使用compare-Method。
To my understanding the same code in Swift does compare the text values. 据我了解,Swift中的相同代码确实比较了文本值。 That is nice.
那很好。 A lot of programing language work like that.
像这样的许多编程语言都可以工作。 But what do I have to do to check if these two values refer to the same object?
但是,我该怎么做以检查这两个值是否指向同一个对象?
For objects of class type you can you the ===
operator to check whether two objects refer to the same instance. 对于类类型的对象,可以使用
===
运算符检查两个对象是否引用同一实例。 However, you ask specifically about strings. 但是,您专门询问字符串。 Strings in swift are not of class type - they are values .
swift中的字符串不是类类型-它们是值 。 The
===
operator will not work for them - the same way as it does not work for integers. ===
运算符不适用于它们-相同的方法不适用于整数。 So the answer to your question - how to check if two strings are the same instance - in Swift is: it is not possible. 因此,在Swift中,如何检查两个字符串是否为同一实例的问题的答案是:不可能。 With strings in Swift you should use normal operators like
==
etc. only. 在Swift中使用字符串时,应仅使用
==
等常规运算符。
You can't as strings are values types, not object types. 您不能因为字符串是值类型,而不是对象类型。 The
===
operator only works with object types (of AnyObject
) but String
is of type Any
. ===
运算符仅适用于对象类型( AnyObject
),但String
是Any
类型。
6> "abc" === "abc"
repl.swift:6:1: error: type 'String' does not conform to protocol 'AnyObject'
"abc" === "abc"
^
Swift.lhs:1:5: note: in initialization of parameter 'lhs'
let lhs: AnyObject?
^
6> var str : String = "abc"
str: String = "abc"
7> str === str
repl.swift:7:1: error: type 'String' does not conform to protocol 'AnyObject'
str === str
^
Swift.lhs:1:5: note: in initialization of parameter 'lhs'
let lhs: AnyObject?
^
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.