天天看点

Swift 2.0中打印函数的用法

       在今年的苹果全球开发者大会上(Worldwide Developers Conference, WWDC 2015),苹果发布了Swift 2.0版本,对1.x版本,2.0版本做了许多细节上的改动,这篇文章便来谈谈打印函数的变化。

       最近一直在看Swift语言,许多书上打印“Hello World”的语句是这样子的:

println("Hello, World")
           

       但是,如果你在Xcode7中的playground输入这句语句,会出现下面的报错:

Swift 2.0中打印函数的用法

       在控制台,输出的是:

Swift 2.0中打印函数的用法

       这是什么情况呢?简单地说就是,在2.0之后的版本中,“println”这个函数现在已经没有了,取而代之的是“print”。所以,想要打印“Hello World”,需要这样子写:

print("Hello, World")
           

       熟悉Swift语言的同学应该知道,“print”函数在Swift 1.x版本中也有,主要功能是打印一句话,且不会自动换行。但是在2.0之后的版本中,“print”函数在默认的情况下是自动换行的。

       有同学会问,那么在2.0之后的版本中,想要打印一句话并且不换行,该怎么写?我们来看看“print”函数的声明语句:

/// Writes the textual representations of `items`, separated by
/// `separator` and terminated by `terminator`, into the standard
/// output.
///
/// The textual representations are obtained for each `item` via
/// the expression `String(item)`.
///
/// - Note: to print without a trailing newline, pass `terminator: ""`
///
/// - SeeAlso: `debugPrint`, Streamable`, `CustomStringConvertible`,
///   `CustomDebugStringConvertible`
public func print(items: Any..., separator: String = default, terminator: String = default)
           

       可以发现,“print”函数的传入参数有三个:items, separator, terminator。“terminator”这个参数的主要作用是,在打印的字符串末尾加上指定的后缀,默认值为"\n"。在函数说明中,有这么一句注释:

/// - Note: to print without a trailing newline, pass `terminator: ""`
           

       也就是说,想要打印一句话并且不换行,需要向“terminator”这个参数传递一个空字符串""。因此,打印“Hello World”且不换行,需要像下面这样子写:

print("Hello, World", terminator:"")
           

       好了,以上就是有关Swift 2.0之后版本中打印函数的一些小变化。