如何强制自选的斯威夫特阵列(很好) [英] How to coerce a Swift array of optionals (nicely)

查看:106
本文介绍了如何强制自选的斯威夫特阵列(很好)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用SWIFT 2.1

Using Swift 2.1

我要寻找到非可选类型的数组分配给可选类型的数组,其中类型是相同的一个很好的方式。这里是一些什么我都试过:

I am looking for a nice way to assign an array of non-optional types to an array of optional type, where the type is the same. Here is some of what I have tried:

var foos: [Int?] = []
let bars: [Int] = []

foos = bars // Error: Cannot assign value of type '[Int]' to type '[Int?]'
foos = bars as [Int?] // Error: Cannot convert value of type '[Int]' to type '[Int?]' in coercion
foos = bars as? [Int?] // Error: 'Int?' is not a subtype of 'Int'
foos = bars.map { $0 } // Works but I think there must be a better way

指定一个非可选类型可选类型斯威夫特工作正常。我不明白为什么这会不会也是一个数组工作。

Assigning a non-optional type to an optional type works fine in Swift. I don't understand why this wouldn't also work for an array.

var foo: Int? = nil
let bar: Int = 0

foo = bar // Works fine

任何想法?

推荐答案

您可以使得语法多一点可口用了几个泛型函数,将看起来像类型转换:

You can make the syntax a little more palatable using a couple of generic functions that will look like type casting:

var foos: [Int?]   = []
let bars: [Int]    = []
let fums: [Int64?] = []

func CastArray<T, U>(array:[T?]) -> [U?]
{ return array.map({ $0 as! U? }) } 

func CastArray<T, U>(array:[T]) -> [U?]
{ return array.map({ $0 as? U }) } 

foos = CastArray(bars)
foos = CastArray(fums)

这篇关于如何强制自选的斯威夫特阵列(很好)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆