swift basic for leetcode

输入输出基础

主要学习使用swift怎么输入输出

输出

print(items: separator: terminator:)
`
  • items 双引号包括在内的需要输出的变量

  • separator(可选) 允许使用间隔符分割items 默认使用单空格(“ “)分割

  • terminator(可选) 允许在输出结尾添加特殊符号如换行(“\n”)与制表符(“\t”) 默认使用换行符

使用实例

例子1:基本用法

没有使用terminator 默认为”\n”

print("Hello AisLing!")
print("Hello Swift")
`

Output

Hello AisLing!
Hello Swift
`

例子2:打印指定结尾符号

print("Hello AisLing!", terminator: " ") 

print("Hello Swift")
`

Output

Hello AisLing! Hello Swift
`

例子3:打印带分隔符

使用”. “分割多个dayitems

print("New Year", 2022, "See you soon!", separator: ". ")
`

Output

New Year. 2022. See you soon!
`

例子4:打印变量与字符串

let count = 10
let fruteType = "apple"
print ("Hello \(count) \(fruteType)")
print ("Hello" + " \(count) " + fruteType)
`

Output

Hello 10 apple
Hello 10 apple
`

输入

输入的场景不适用Xcode playground场景

readLine()函数

/// - Parameter strippingNewline: If `true`, newline characters and character
/// combinations are stripped from the result; otherwise, newline characters
/// or character combinations are preserved. The default is `true`.
/// - Returns: The string of characters read from standard input. If EOF has
/// already been reached when `readLine()` is called, the result is `nil`.
public func readLine(strippingNewline: Bool = true) -> String?
`
  • strippingNewline 换行符是否从结果中剥离 默认剥离

  • 返回值为可选值 使用时需要注意

例子1:基本用法

print("Enter your favorite programming language:")
if let name = readLine() {
print("Your favorite programming language is \(name).")
}
`

Output

Enter your favorite programming language:
Swift
Your favorite programming language is Swift.
`