Swift中的字符和字符串 [英] Characters and Strings in Swift

查看:137
本文介绍了Swift中的字符和字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

阅读文档此答案,我看到我可以初始化一个Unicode字符以下列方式之一:

  let narrowNonBreakingSpace:Character =\u {202f}
let narrowNonBreakingSpace =\u {202f}

据我所知,第二个实际上是一个String 。与Java不同,它们都使用双引号(而不是字符的单引号)。我看过几个例子,虽然,第二种形式(不 Character )被使用,即使该变量只持有一个单一的字符。是那个人只是懒惰或忘记写 Character ?还是Swift照顾所有的细节,我不需要麻烦呢?如果我知道我有一个常量只包含一个Unicode值,我应该总是使用 Character

当未指定类型时,Swift将在创建变量或常量时从字符串文字中创建一个 String 长度。因为 String 在Swift和Cocoa / Foundation方法中非常流行,所以你应该使用它,除非你特别需要一个 Character - 然后你每次需要使用它时,只需要转换为 String


Reading the documentation and this answer, I see that I can initialize a Unicode character in either of the following ways:

let narrowNonBreakingSpace: Character = "\u{202f}"
let narrowNonBreakingSpace = "\u{202f}"

As I understand, the second one would actually be a String. And unlike Java, both of them use double quotes (and not single quotes for characters). I've seen several examples, though, where the second form (without Character) is used even though the variable is only holding a single character. Is that people just being lazy or forgetting to write Character? Or does Swift take care of all the details and I don't need to bother with it? If I know I have a constant that contains only a single Unicode value, should I always use Character?

解决方案

When a type isn't specified, Swift will create a String instance out of a string literal when creating a variable or constant, no matter the length. Since Strings are so prevalent in Swift and Cocoa/Foundation methods, you should just use that unless you have a specific need for a Character—otherwise you'll just need to convert to String every time you need to use it.

这篇关于Swift中的字符和字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆