首页 > 解决方案 > 尝试以三元表达式返回

问题描述

我有一个 Swift 应用程序。

Expected expression after '?' in ternary expression从 Xcode 编译器 收到错误

private func getContentPre(highlight: Highlight) -> String!

    {
        highlight.contentPre.count == 0 ? return ">" : return highlight.contentPre
    }

苹果文档说:

在此处输入图像描述

为什么不能return像使用 if 语句那样使用三元表达式?

标签: iosswiftternary

解决方案


你应该像这样重写你的函数。这将评估contentPre变量的计数并返回适当的响应。

private func getContentPre(highlight: Highlight) -> String! {
    return highlight.contentPre.count == 0 ? ">" :  highlight.contentPre
}

但是,您contentPre应该String使用.isEmpty它,因为它比检查 a 的长度更具性能String

private func getContentPre(highlight: Highlight) -> String! {
    return highlight.contentPre.isEmpty ? ">" :  highlight.contentPre
}

推荐阅读