Swift Combine 响应式 Demo

一个Combine Demo。 Combine是苹果发布的响应式框架,iOS13一起发布的,所以最低iOS13才能使用。

做了一个简单登录界面的异步处理演示。

页面逻辑说明:

  1. 获取验证码按钮是否启用(isEnabled)跟手机号输入框值是否有效有关。输入11位长度字符串获取验证码按钮isEnabled变为true。

  2. 登录按钮是否启用(isEnabled)跟三个控件状态或值相关联,分别是:手机号输入框内容、验证码输入框内容以及同意隐私政策开关。三个控件同时满足校验才能改登录按钮isEnabled位true。

代码部分

创建三个用@Published修饰的变量,用于接受控件内容

Swift 复制代码
@Published var phone: String? = ""
@Published var verifyCode: String? = ""
@Published var isAgree: Bool = false

@IBAction func phoneChanged(_ sender: UITextField) { phone = sender.text }
@IBAction func verifyCodeChanged(_ sender: UITextField) { verifyCode = sender.text }
@IBAction func agreeChanged(_ sender: UISwitch) { isAgree = sender.isOn }

创建校验手机号发布者,输出值为布尔类型

Swift 复制代码
// 校验手机号的发布者
var phoneValid: AnyPublisher<Bool, Never> {
    $phone
        .map { $0?.count == 11 ? true : false }
        .eraseToAnyPublisher()
    }

创建校验验证码发布者

Swift 复制代码
// 校验验证码的发布者
var verifyCodeValid: AnyPublisher<Bool, Never> {
    $verifyCode
        .map { code in
            guard                   // 验证码校验逻辑(实际情况按照需求自定义)
                let code = code,    // 值不能为nil
                code.count == 4,    // 长度为4
                let _ = Int(code)   // 能转为Int
            else { return false }   // 以上三种全部满足返回true,否则返回false

            return true
        }
        .eraseToAnyPublisher()      // 抹去类型转为AnyPublisher
}

合并三个发布者 - CombineLatest

Swift 复制代码
// 融合三个发布者
Publishers.CombineLatest3(phoneValid, verifyCodeValid, $isAgree)
    .map { $0 && $1 && $2 }                 // 筛选逻辑
    .receive(on: RunLoop.main)              // 在主线程接受
    .assign(to: \.isEnabled, on: toLogin)   // 结果分配
    .store(in: &subscriptions)              // 返回值Cancellable对象储存在全局容器中

Demo代码地址

相关推荐
代码的小搬运工1 小时前
【iOS】3G-Share仿写总结
macos·ios·cocoa
2501_916007472 小时前
iOS和macOS应用程序性能分析和优化工具使用综合指南
android·macos·ios·小程序·uni-app·iphone·webview
智购科技无人售货机工厂3 小时前
自动售货机硬件选型避坑:单片机 / 树莓派 / ESP32 怎么选?~YH
人工智能·单片机·嵌入式硬件·r语言·swift·perl·symfony
游戏开发爱好者83 小时前
iOS开发IDE有哪些 Xcode 和 快蝎 轻量替代方案
ide·vscode·ios·个人开发·xcode·swift·敏捷流程
ZZH_AI项目交付1 天前
同一套前摄心率算法,为什么 iPhone 16 Pro 稳,iPhone XR 会失准?
ios·app·ai编程
DeMinds1 天前
内容没有丢,我为什么总在重新整理?|DeMinds 如何让工作接着继续
ios·github·markdown
apd_csdn1 天前
清华邮箱苹果邮件app设置(全)
ios·thu
MDM.Plus1 天前
从“遥控”到“自治”:苹果 MDM 技术的代际跨越与业务重构
ios·智能手机·重构·mdm
黑化旺仔1 天前
iOS - 天气预报仿写总结
ios
Coffeeee1 天前
ios零基础的Android开发能否靠AI让老板省一笔人工费呢
android·ios·ai编程