You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在函数参数中传递结构体?如何用结构体替代Bool传参?

分析你的代码问题 & 结构体参数传递指南

首先看你现有代码里的核心问题:

  • 你定义的struct Alert里的alert和info是实例属性,也就是说必须先创建Alert的实例(比如let alertInstance = Alert())才能访问这些属性,直接写Alert.info是编译错误的——类型本身不能直接访问实例级别的属性。
  • 另外,你想用结构体区分两种提示类型(不用Bool)的需求,目前的Alert结构体只是存储了两个固定字符串,没真正发挥“类型标识”的作用,有点浪费结构体的特性。

正确实现:用结构体定义类型标识(替代Bool)

如果你想用结构体清晰区分两种提示类型(Alert/Information),最合理的方式是给结构体定义静态预实例,这样既不用Bool,也能直观传递类型:

// 定义结构体,封装提示类型的相关信息
struct AlertType {
    // 存储该类型对应的显示标题(可扩展其他属性,比如图标、优先级等)
    let displayTitle: String
    
    // 预定义两个静态实例,代表你需要的两种类型
    static let alert = AlertType(displayTitle: "Alert")
    static let information = AlertType(displayTitle: "Information")
}

如何在函数参数中传递结构体

接下来调整你的AskConfirmation函数,把type参数的类型改成AlertType,这样就能直接传递我们预定义的静态实例:

// 调整后的AskConfirmation函数,type参数接收AlertType结构体
func AskConfirmation(type: AlertType, title: String, message: String, completion: @escaping (Bool) -> Void) {
    // 直接使用结构体的属性,比如type.displayTitle
    print("正在展示 \(type.displayTitle): \(message)")
    
    // 你的确认框业务逻辑...
    
    // 执行回调
    completion(true)
}

然后修改你的information和alert函数,调用时直接传递预定义的结构体实例:

func information(message: String) {
    AskConfirmation(
        type: .information, // 直接用静态实例,Swift会自动推断类型
        title: AlertType.information.displayTitle, // 从结构体取标题,避免硬编码
        message: message,
        completion: { [weak self] _ in // 加[weak self]避免循环引用
            self?.dismiss(animated: true)
        }
    )
}

func alert(message: String) {
    AskConfirmation(
        type: .alert,
        title: AlertType.alert.displayTitle,
        message: message,
        completion: { [weak self] _ in
            self?.dismiss(animated: true)
        }
    )
}

额外:结构体参数的通用传递方式

如果以后需要传递更复杂的结构体(包含多个属性),方法也是一致的:

  1. 先定义结构体,封装你需要传递的所有数据:
struct AlertConfig {
    let type: AlertType
    let title: String
    let message: String
    let shouldAutoDismiss: Bool
}
  1. 函数参数指定结构体类型:
func showAlert(with config: AlertConfig) {
    print("展示提示:\(config.title) - \(config.message),自动关闭:\(config.shouldAutoDismiss)")
}
  1. 创建结构体实例并传递:
let infoConfig = AlertConfig(
    type: .information,
    title: "信息提示",
    message: "这是一条重要通知",
    shouldAutoDismiss: true
)
showAlert(with: infoConfig)

这种方式比用Bool更清晰(不会出现true到底对应Alert还是Information的歧义),而且结构体可以随时扩展属性,灵活性更高。

内容的提问来源于stack exchange,提问作者Nishad Arora

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.22 08:00:41