如何改变" [任何]"到"任何......"

时间:2018-06-07 03:19:47

标签: swift

首先,我想为我的项目提供私人日志。因此,我创建了一个函数tkprint(items: Any...)来调用系统日志print(items: Any...)

但是,在功能tkprint(items: Any...)中,我只能获得Any。所以,我想知道如何改变" [Any]"到"任何"。

我知道我可以将物品减少到物品来解决问题。

示例:

func somewhere() {
    tklog("Hello", "swift", "!")
}
func tklog(_ items: Any...) {
    //items is ["Hello", "swift", "!"]
    tkprint(items)
}
func tkprint(_ items: Any...) {
    //items is [["Hello", "swift", "!"]]
    print(items)
}

打印:

  

[[你好,swift,!]]

目标:

func somewhere() {
    tklog("Hello", "swift", "!")
}
func tklog(_ items: Any...) {
    //items is ["Hello", "swift", "!"]
    tkprint(parse(items))
}
func tkprint(_ items: Any...) {
    //items is ["Hello", "swift", "!"]
    print(parse(items))
}
func parse(items: [Any]) -> Any... {
    //items is ["Hello", "swift", "!"]
    //TODO: parse
    return "Hello", "swift", "!"
}

打印:

  

Hello swift!

1 个答案:

答案 0 :(得分:0)

您无法为方法Any...返回parse(_ items: Any),您可以返回AnyString进行打印。

func somewhere() {
    tklog("Hello", "swift", "!")
}
func tklog(_ items: Any...) {
    //items is ["Hello", "swift", "!"]
    tkprint(parse(items))
}
func tkprint(_ items: Any...) {
    //items is ["Hello", "swift", "!"]
    print(parse(items))
    // Hello swift !
}
func parse(_ items: Any) -> Any {
    //items is ["Hello", "swift", "!"]
    if let items = items as? [String] {
        return items.reduce("") { "\($0) \($1)" }
    } else {
        return ""
    }
}

func parse(_ items: Any...) -> [Any] {
    return items.map{ $0 }
    // ["hello", "swift", "!"]
}

func parse(_ items: Any...) -> Any {
    return items.map{ $0 }
    // ["hello", "swift", "!"]
}