如何在Swift中使用三元运算符

时间:2018-10-09 21:35:07

标签: swift

我想在ishighestversion中使用三元运算符:

func printThis(_ items: Any...)

我试图简化此操作:

import Foundation

class PrintHelper {

/// This will help us to stop printing any thing to the console if we want at any time to look for something important.
static var printIsAllowed: Bool {
    return true // set false to stop printing ..
}

/// Print method that check if print is allowed or not.
///
/// - Parameter items: Zero or more items to print.
static func printThis(_ items: Any...) {
    if printIsAllowed {
        print(items)
    }else{
        return
    }
}

通过编写:

if printIsAllowed { print(items) }else{ return }

然后出现错误!

2 个答案:

答案 0 :(得分:1)

您甚至不需要三元运算符,甚至不需要 else 。足够了:

static func printThis(_ items: Any...) {
    if printIsAllowed {
        print(items)
    }
}

答案 1 :(得分:0)

如果您真的真的要使用三元运算符,请更改此功能:

static func printThis(_ items: Any...) {
    let _ = printIsAllowed ? {print(items)}() : ()
}

您可以这样称呼它:

PrintHelper.printThis("Hello World!") //prints ["Hello World!"]