String Swift字符串常量的类型是否与字符串文本的类型不同?

String Swift字符串常量的类型是否与字符串文本的类型不同?,string,swift,types,constants,literals,String,Swift,Types,Constants,Literals,在Swift 2.1中,下面的代码段生成一个错误 var str = "Hello, playground!" // Success Case if "!" == str.characters.last { print("Tone it down please") } // Fail Case let bang = "!" if bang == str.characters.last { // this line won't compile print("Tone it

在Swift 2.1中,下面的代码段生成一个错误

var str = "Hello, playground!"

// Success Case
if "!" == str.characters.last {
    print("Tone it down please")
}

// Fail Case
let bang = "!"

if bang == str.characters.last {  // this line won't compile
    print("Tone it down please")
}
编译器错误显示:

二进制运算符“==”不能应用于“String”类型的操作数 和“_元素?”

那么,在这种情况下,推荐使用常量而不是文字的方法是什么呢?(我正在学习Swift,因此请随时提及是否有更快捷的方法来处理此类比较检查。)

谢谢

对于“失败案例”,这是因为
str.characters.last
是可选的,是
字符
,但
bang
字符串

您可以安全地展开并与
进行比较,如果让。。。其中
,并使用
String()
字符
更改为
字符串
,以进行比较:

if let last = str.characters.last where String(last) == bang {
    print("Tone it down please")
}

正如错误所说,第一个运算符是
字符串
,第二个运算符是可选的
字符

但您已经演示了如何将字符串转换为
字符?
,因此我们可以使用它:

if bang.characters.last == str.characters.last {
    print("Tone it down please")
}

您知道,
bang.characters.last
将只返回
“!”
,但现在它将与
str.characters.last
的类型相同,因此比较它们将非常简单。

感谢您的讨论。下面是我自己的答案,通过消除无关的选项来改进说明,并演示类型推断的好坏:

let a:String = "!"              // type is String
let b:Character = "!"           // type is Character
let c = "!".characters.last!    // type is _Element
let bang = "!"                  // inferred type is String

if "!" == a { print("literal matches string") }
if "!" == b { print("literal matches Character") }
if "!" == c { print("literal matches _Element") }

if a == b { print("a matches b") }      // Err: 'String' to 'Character'
if a == c { print("a matches c") }      // Err: 'String' to '_Element' 
if b == c { print("b matches c") }      // OK: 'Character' to '_Element' 
结论:如果上下文提示,由单个带引号的字符组成的文字可以识别为
字符串
,或
字符
(或等效为
\u元素

重要的是:常量的类型在声明时永久建立。文字的类型是从其上下文推断出来的,因此同一文字在不同的上下文中可能有不同的类型


提供给文本的灵活类型推断不适用于常量。

不确定这是否完全相关,但我发现这篇文章,因为我在
字符之间转换时遇到问题。首先是
字符。最后是
Int

如果这有助于任何人:

let element = characters.first! // the ! is important
let myString = String(element) 
let myInt = Int(myString) // may be nil if character is not an int

相关人员没有谈论它(或者我可能没有找到它),但如果您的“成功案例”奏效,我不会感到惊讶,因为当在单个字符串和字符之间使用
==
运算符时,Swift会自动将
“!”
化名为
字符;这种机制不适用于
bang
,因为它不是文本。但这只是一个猜测,所以我没有把它包括在我的答案中。我认为你的“猜测”是正确的。“!”可以是字符串文字(默认值)和字符文字(从上下文推断时)<代码>让bang=Character(!”
编译“失败案例”所以这个问题实际上与期权无关<代码>让砰的一声=“!”;如果bang==str.characters.last!{}
也不编译。谢谢!或者,我发现我也可以说:
let bang=“!”。characters.last
这个问题的关键点与期权无关!再次感谢。错误实际上并没有说第二个字符是可选的
字符。它说它是一个可选的
\u元素
,我不认识它。但是我接受你关于从字符串转换到最后一个字符的观点。谢谢(请参阅我的评论中发布的变体,了解前面的答案,以找到转换为字符的另一个位置。)