首页 > 代码库 > Swift - String, Character

Swift - String, Character

String, Character

String 在 Swift 中使用双引号(”)作为界限:

let greeting = "Hello!"  // greeting‘s type is String

Character 可以从string初始化,只要只包含一个字符:

let chr: Character = "H" // valid
let chr2: Character = "??" // valid
let chr3: Character = "abc" // invalid - multiple grapheme clusters

字符串插入值

String interpolation 允许注入一个表达式,可以是任何值,包括字符串,整数,浮点数和其他各种。

语法是用一个斜杠,后面紧跟着一对括号括起来的值:\(value)。任何有效的表达式都可以出现在括号里,包括函数调用。

let number = 5
let interpolatedNumber = "\(number)"  // string is "5"
let fortyTwo = "\(6 * 7)"             // string is "42"

let example = "This post has \(number) view\(number == 1 ? "" : "s")"
// It will output "This post has 5 views" for the above example.
// If the variable number had the value 1, it would output "This post has 1 view" instead.

特殊的字符

  • \0
    空字符
  • \
    斜杠
  • \t
    tab符
  • \v
    纵向tab
  • \r
    回车符
  • \n
    换行符
  • \”
    双引号
  • \’
    单引号
  • \u{n}
    Unicode 符号

比如:

let message = "Then he said, \"I \u{1F496} you!\""

print(message) // Then he said, "I ?? you!"
<script type="text/javascript"> $(function () { $(‘pre.prettyprint code‘).each(function () { var lines = $(this).text().split(‘\n‘).length; var $numbering = $(‘
    ‘).addClass(‘pre-numbering‘).hide(); $(this).addClass(‘has-numbering‘).parent().append($numbering); for (i = 1; i <= lines; i++) { $numbering.append($(‘
  • ‘).text(i)); }; $numbering.fadeIn(1700); }); }); </script>

    Swift - String, Character