SwiftUI“不能在属性初始值设定项中使用实例成员‘numberOfDevice’;属性初始值设定项在“自我"可用之前运行";错误 [英] SwiftUI "Cannot use instance member 'numberOfDevice' within property initializer; property initializers run before 'self' is available" error

查看:25
本文介绍了SwiftUI“不能在属性初始值设定项中使用实例成员‘numberOfDevice’;属性初始值设定项在“自我"可用之前运行";错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

粗体行(即 var text: String...)给出了一个不能在属性初始值设定项中使用实例成员 'numberOfDevice';属性初始值设定项在自我"可用之前运行";错误.我需要初始化吗?如果是在哪里?有什么不同的解决方案吗?

The bolded line (ie var text: String...) gives a "Cannot use instance member 'numberOfDevice' within property initializer; property initializers run before 'self' is available" error. Do I need an init? If so where? Is there a different solution?

struct PairView: View {
    var theClass = BluetoothManager()   
    init() {theClass.viewDidLoad()}     

    var body: some View {
        List {
            ForEach(0..<BluetoothManager.peripheralArray.count) {   number in  //iterates thru 0 to array's count
            ConnectionView(numberOfDevice: number)      // create a ConnectionView for each number
        }
     }
  }
}

//-------

struct ConnectionView: View {
    
    var numberOfDevice: Int
    **var text: String = (BluetoothManager.peripheralArray[numberOfDevice]?.name)!**  
    // 'name' is a String property of the B.M. class's array's 'numberOfDevice index.'

    var body: some View {
        ZStack{
            RoundedRectangle(cornerRadius: 10.0).fill(Color.blue)
            Text(text).foregroundColor(Color.black)
        }
    }
}

推荐答案

您可以使用速记的只读计算属性.

You can use read-only computed property with short-hand.

var text: String { 
       return (BluetoothManager.peripheralArray[numberOfDevice]?.name)!
}  

这篇关于SwiftUI“不能在属性初始值设定项中使用实例成员‘numberOfDevice’;属性初始值设定项在“自我"可用之前运行";错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆