简体   繁体   中英

How to initialise closure variable in swift?

This is my main struct. and I am trying to get a call back when listView selects and item.

struct Home: View {

    @State var selectdItem : Int = 0
    var body: some View {
        VStack{

            listView(onselecteditem: {selectdItem in
                self.selectdItem = selectdItem
            })
            resultView(selectedItem: self.$selectdItem)

        }

    }
}

And I would like to initialise my closure variable in init in this struct. it works without init, but i have to use the init.

struct listView : View
{
    var onSelectedItem : (Int) -> Void

    init(onselecteditem : (Int) -> Void) {

     // I would like to initialise onSelected closure variable here.   
    }

    var body : some View
    {
        List(1..<10)
        {
            item in
            Text("Item \(item)").onTapGesture {
                self.onSelectedItem(item)
            }
        }
    }
}

You can initialize closure variable as,

init(onselecteditem : @escaping (Int) -> Void) {
    self.onSelectedItem = onselecteditem
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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