是否可以实现包含nil元素的Swift SequenceType?
发布时间:2020-12-14 05:32:01  所属栏目:百科  来源:网络整理 
            导读:我想实现一个可以包含nil元素的自定义可迭代类,类似于[Any?].符合SequenceType主要是有效的,除了GeneratorType.next()的契约,它表示当所有元素都用尽时它应该返回nil.有解决方法吗? 这是一个(非常愚蠢)的例子: struct OddSequence : SequenceType { func
                
                
                
            | 
                         
 我想实现一个可以包含nil元素的自定义可迭代类,类似于[Any?].符合SequenceType主要是有效的,除了GeneratorType.next()的契约,它表示当所有元素都用尽时它应该返回nil.有解决方法吗?
 
 这是一个(非常愚蠢)的例子: 
  
  
                          struct OddSequence : SequenceType {
    func generate() -> GeneratorOf<Int?> {
        var current = 0
        return GeneratorOf<Int?>() {
            if current >= 6 {
                return nil
            }
            current++
            if current % 2 == 0 {
                return current
            } else {
                return Optional(nil)
            }
        }
    }
}
for x in OddSequence() {
    println(x)
} 
 输出: nil Optional(2) nil Optional(4) nil Optional(6) 生成器为每个元素返回一个可选的(可以是Optional(nil)), 另请参阅Swift博客中的“Optionals Case Study: valuesForKeys”,了解nil和.之间的区别 Swift 2更新: struct OddSequence : SequenceType {
    func generate() -> AnyGenerator<Int?> {
        var current = 0
        return anyGenerator {
            if current >= 6 {
                return nil
            }
            current++
            if current % 2 == 0 {
                return current
            } else {
                return Optional(nil)
            }
        }
    }
}
for x in OddSequence() {
    print(x)
}
(编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!  | 
                  
相关内容
- 最新邮箱匹配正则(邮箱前缀可包含"_")
 - VB.NET FTP登录类
 - Cocos Creator 生命周期回调(官方文档摘录)
 - 去掉vue 中的代码规范检测两种方法(Eslint验证)
 - jsf-2 – 如果编写@managed bean注释并在faces-config.xml中
 - React Native--flexbox
 - oracle to_char函数将number转成string
 - 如何在postgreSQL(Redshift)数据库中的“大”数据上使用tid
 - PostgreSQL::Snapshots aka Materialized Views
 - c# – 禁用Webview垂直滚动以保持父元素滚动
 
