Swift Xcode 12.5编译器错误&x27;无';不能在上下文中使用,应为类型';someType';

Swift Xcode 12.5编译器错误&x27;无';不能在上下文中使用,应为类型';someType';,swift,conditional-operator,xcode12.5,Swift,Conditional Operator,Xcode12.5,这两段代码之间有什么区别 cellModels.append(contentsOf: [].compactMap { $0.condition ? .init(text: $0.text, backgroundColor: $0.color, action: $0.action) : nil }) cellModels.append(contentsOf: [].compactMap { if $0.condition { return

这两段代码之间有什么区别

cellModels.append(contentsOf: [].compactMap { $0.condition ? .init(text: $0.text, backgroundColor: $0.color, action: $0.action) : nil })


cellModels.append(contentsOf: [].compactMap {
            if $0.condition {
                return .init(text: $0.text, backgroundColor: $0.color, action: $0.action)
            } else {
                return nil
            }
        })
更新到Xcode 12.5后,第一个代码不再编译

操场的一些代码片段。在Xcode 12.5中尝试一下

struct SomeStruct {
var str: String
}
var arr1: [SomeStruct] = []
arr1.append(contentsOf: ["123123", "2", "332", "124r132q", "123"].compactMap { $0.count == 3 ? .init(str: $0) : nil })
arr1.append(contentsOf: ["123123", "2", "332", "124r132q", "123"].compactMap {
                if $0.count == 3 {
                    return .init(str: $0)
                } else {
                    return nil
                }})

将代码分为两部分会有所帮助

var mappedArray: [SomeStruct] = ["123123", "2", "332", "124r132q", "123"].compactMap { $0.count == 3 ? .init(str: $0) : nil }

arr1.append(contentsOf: mappedArray)

请显示一个。这可能是因为三元语句对于它来说很复杂。当我尝试将代码分成两部分时,它只是按照预期编译和工作。根据操作,compactMap{$0.count==3?.init(str:$0):nil}arr1.append(contentsOf:mappedArray)@Nina有效;你可能应该给出一个真实的答案。这是尼娜的评论。你应该让尼娜给你答案,这样你就可以接受它并奖励你的声誉。如果尼娜回答,我会删除我的。没问题,只要它有帮助