Swift 2.0中打印函数的用法

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

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

println("Hello, World")

       

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



       在控制台,输出的是:


       

       这是什么情况呢?简单地说就是,在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之后版本中打印函数的一些小变化。



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值