[Swift/SwiftUI] 调用无参方法传参错误排查求助
SwiftUI 编译错误修复:"Argument passed to call that takes no arguments"
问题描述
在ScheduleManagementView.swift第35行调用方法时出现编译错误:Argument passed to call that takes no arguments。尝试将NavigationLink替换为Button、添加/移除$符号等操作后,问题仍未解决。
相关代码
struct ScheduleManagementView: View { @State private var selectedDate = Date() @State private var selectedEmployee = "" @State private var startTime = Date() @State private var endTime = Date() @State private var showScheduleList = false @State private var showAlert = false @State private var schedules: [ShiftSchedule] = [] // var body: some View {... NavigationLink(destination: ScheduleManagementView(schedules: $schedules)) { Image(systemName: "calendar") .font(.system(size: 60)) } NavigationLink(destination: ExpensesCounterView(schedules: $schedules)) { Image(systemName: "dollarsign.circle") .font(.system(size: 60)) } }
错误原因
当前定义的ScheduleManagementView结构体所有属性均为@State修饰的私有属性,Swift会自动生成无参初始化器。但你在创建实例时传入了schedules: $schedules参数,与默认初始化器不匹配,因此触发编译错误。
解决方案
方案1:支持外部传入绑定的schedules(适用于需要共享状态的场景)
将schedules的@State改为@Binding,并添加自定义初始化器:
struct ScheduleManagementView: View { @State private var selectedDate = Date() @State private var selectedEmployee = "" @State private var startTime = Date() @State private var endTime = Date() @State private var showScheduleList = false @State private var showAlert = false @Binding var schedules: [ShiftSchedule] // 改为@Binding // 自定义初始化器 init(schedules: Binding<[ShiftSchedule]>) { self._schedules = schedules // 其余@State属性使用默认值,无需额外初始化 } // body代码保持不变... }
修改后,原NavigationLink的调用方式就可以正常工作。
方案2:使用无参初始化(适用于无需共享状态的场景)
如果ScheduleManagementView不需要外部传入schedules,直接移除初始化参数:
NavigationLink(destination: ScheduleManagementView()) { Image(systemName: "calendar") .font(.system(size: 60)) }
额外注意
对于ExpensesCounterView的调用,需要确认它是否定义了接受Binding<[ShiftSchedule]>的初始化器。如果没有,需对ExpensesCounterView做类似上述的修改,否则同样会触发相同错误。
内容的提问来源于stack exchange,提问作者iliwnl
相关产品推荐
相关产品推荐

