我有一个类,它有两个已发布的变量:
class Controller: ObservableObject {
    @Published var myArray: Array<Int>: [1,2,3,4,5]
    @Published var currIndex: Int = 0
    func currItem() -> Int {
        return myArray[curIndex]
    }
}我希望我的观点是订阅函数"currItem“而不是currIndex变量,是否有一种优雅的方法来实现它?在不订阅函数的情况下,我需要编写一些样板代码:
struct myView: View {
    var controller: Controller = Controller()
    var body: some View {
        Text(controller.myArray[controller.currIndex]) // <-- Replace this with controller.currItem()        
    }
}发布于 2021-03-29 07:49:04
你可以做得更好,就像这样:
import SwiftUI
struct ContentView: View {
    
    @StateObject var controller: Controller = Controller()
    
    var body: some View {
        Text(controller.currItem?.description ?? "Error!")
    }
}class Controller: ObservableObject {
    
    @Published var myArray: Array<Int> =  [1,2,3,4,5]
    @Published var currIndex: Int? = 0
    
    var currItem: Int? {
        
        get {
            
            if let unwrappedIndex: Int = currIndex {
                
                if myArray.indices.contains(unwrappedIndex) {
                    return myArray[unwrappedIndex]
                }
                else {
                    print("Error! there is no such index found!")
                    return nil
                }
                
            }
            else {
                
                print("Error! you did not provide a value for currIndex!")
                return nil
                
            }
            
        }
        
    }
}https://stackoverflow.com/questions/66850308
复制相似问题