简体   繁体   English

从 Function 返回数组(Swift)

[英]Returning Array from Function (Swift)

This is my first question so please, be gentle!这是我的第一个问题,请保持温柔!

I've been debugging my code and searching stackexchange.com for a while, and as best as I can tell, my problem has to do with return an array from a function. I can assure you that this is not a homework question, and I've tried going through Stackoverflow for solutions, and I'm at my wits end!我一直在调试我的代码并搜索 stackexchange.com 一段时间,据我所知,我的问题与从 function 返回数组有关。我可以向你保证这不是家庭作业问题,并且我试过通过 Stackoverflow 寻找解决方案,但我已经束手无策了!

The ActiveModelResponseList is used to display a list of acceptable responses to the user, arranged in a List form: ActiveModelResponseList用于向用户显示可接受的响应列表,以List形式排列:

struct ActiveModelResponseList: View {  
    var activeModel: ActiveModel  
    var body: some View {  
        List(activeModel.validResponses()) {  /* XCode error: "Cannot convert value of type  
                                                             '[ValidResponse]' to expected  
                                                             argument type 'Range<Int>'" */  
  
            HStack {  /* XCode error: "Contextual closure type '() -> TupleView<(Text, Text, Spacer)>'
                                      expects 0 arguments, but 1 was used in closure body" */  
                Text($0.response)  
                Text($0.narrative)  
                Spacer()  
            }.padding(10)  
        }  
    }  
}  

I have tried a number of different ways to restructure the above body , and it's specifically that activeModel.validResponses() that causes the errors.我已经尝试了多种不同的方法来重构上面的body ,特别是activeModel.validResponses()导致了错误。 If I delete it and populate the list with hard coded values, it works just fine.如果我删除它并用硬编码值填充列表,它就可以正常工作。

That function, activeModel.validResponses() comes from the ActiveModel class, as follows:即function, activeModel.validResponses()来自ActiveModel class,如下:

class ActiveModel {
    var baseModel: ModelData
    private var responses: [Int]
    private var activeElement: Int
    
    // Although forThisElement is unused in the base function, ActiveModel still has  
    // such an element, used for other purposes  
  
    public func validResponses() -> [ValidResponse] {
        return (baseModel.validResponses(forThisElement: activeElement))
    }  
}

This, in turn, comes from a base class, ModelData .反过来,这来自基础 class, ModelData Note that forThisElement is not actually required for this function, but is included to maintain polymorphism (ie other models will use it).请注意, forThisElement实际上并不是这个 function 所必需的,但包含在内是为了保持多态性(即其他模型将使用它)。 As you can see, ModelData.validResponses returns a [ValidResponse]如您所见, ModelData.validResponses返回一个[ValidResponse]

class ModelData: Hashable, Codable, Identifiable {  
    var id: Int  
    var valid_response: [String]  
    var valid_response_narrative: [String]  
  
    public func validResponses(forThisElement: Int) -> [ValidResponse] {  
        // forThisElement is currently an unused input variable,  
        // but is required for compatibility with other classes

        var thisResult: [ValidResponse] = []  

        for thisResponse in 0..<valid_response.count {  
            thisResult[thisResponse].id = thisResponse  
            thisResult[thisResponse].response = valid_response[thisResponse]  
            thisResult[thisResponse].narrative = valid_response_narrative[thisResponse]  
        }  
        return thisResult  
    }  
}

The ValidResponse is just an ordinary struct, defined as follows: ValidResponse只是一个普通的结构体,定义如下:

struct ValidResponse: Identifiable, Hashable {
    var id: Int = 0  
    var response: String = "0"  
    var narrative: String = "Default"  
}  

The preview is being generated for an iPod touch (7th generation), I'm using Xcode Version 13.1 (13A1030d), and am compiling using MacOS 12.0.1, on a mid-2015 MacBook Pro.正在为 iPod touch(第 7 代)生成预览,我正在使用 Xcode 版本 13.1 (13A1030d),并在 2015 年年中的 MacBook Pro 上使用 MacOS 12.0.1 进行编译。

I found the following answers on stackexchange, but I feel none the wiser after having read them (and, as these answers are quite dated, I wonder if they're still relevant):我在 stackexchange 上找到了以下答案,但在阅读它们之后我觉得并没有变得更明智(而且,由于这些答案已经过时,我想知道它们是否仍然相关):

Can anyone provide any guidance?谁能提供任何指导?

The first error message is nonsense.第一条错误消息是无稽之谈。 Fix the second and it will disappear.修复第二个,它将消失。

The title of your question is unrelated to your actual problem, which is that you're trying to use a positional parameter from an outer closure.您的问题的标题与您的实际问题无关,即您正在尝试使用外部闭包中的位置参数。 That doesn't work;那是行不通的; they can't propagate that way.他们不能那样传播。 Every new closure scope gets its own set of positional parameters, and HStack.init doesn't use any, as the error tells you.每个新的闭包 scope 都有自己的一组位置参数,并且HStack.init不使用任何参数,正如错误告诉你的那样。

Fix: name the argument.修复:命名参数。

List(activeModel.validResponses()) { response in
  HStack {
    Text(response.response)
    Text(response.narrative)

@Jessy, to clarify, I tried making the following change, but it too didn't work: @Jessy,澄清一下,我尝试进行以下更改,但它也没有奏效:

struct ActiveModelResponseList: View {
    var activeModel: ActiveModel
    var validResponses: [ValidResponse] = []
    var body: some View {
        let someResp = activeModel.validResponses()
        List {
            Text("\(someResp.count)")
        }
    }
}

But, alas, it still doesn't work!但是,唉,它仍然不起作用! It crashes on that let line.它在那条let线上崩溃。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM