最新消息:20210816 当前crifan.com域名已被污染,为防止失联,请关注(页面右下角的)公众号

[已解决]swift获取一个UIColor数组的部分元素存为新数组

Swift crifan 2679浏览 0评论

想要实现:

        let uniqueBackgroundAndHeaderColorArr:[UIColor] = getUniqueHeaderColorArr(1 + headerCharArr.count)
       
print("uniqueBackgroundAndHeaderColorArr=\(uniqueBackgroundAndHeaderColorArr)")
       
let uniqueBackgroundColor:UIColor = uniqueBackgroundAndHeaderColorArr[0]
        let uniqueHeaderColorArr:[UIColor] = uniqueBackgroundAndHeaderColorArr[1…uniqueBackgroundAndHeaderColorArr.count]

Cannot subscript a value of type ‘[UIColor]’

搜:

swift array part elements save new array

swift   part element new array

The Swift Programming Language (Swift 2.1): Collection Types

有个:

.removeAtIndex(0)

.removeLast()

有空可以用用。

Arrays and their Methods in Swift — Coding Explorer Blog

swift   part of  array

New Array from Index Range Swift – Stack Overflow

What is a slice in Swift? – Stack Overflow

…三个点 变成 ..两个点:

let uniqueHeaderColorArr:[UIColor] = uniqueBackgroundAndHeaderColorArr[1..uniqueBackgroundAndHeaderColorArr.count]

结果:

Use of unresolved identifier ‘..’

然后去试试:

        let uniqueHeaderColorArr = uniqueBackgroundAndHeaderColorArr[1…uniqueBackgroundAndHeaderColorArr.count]

结果竟然可以通过编译了。

但是感觉像是uniqueHeaderColorArr是slice类型,而不是array

希望搞懂:

[已解决]Swift中如何获得一个变量的类型type

打印出来结果是:

ArraySlice<UIColor>

-》不是我想要的:

Array<UIColor>

所以要再去试试:

如何才能,从一个数组中,取得部分元素,成为一个新的数组

New Array from Index Range Swift – Stack Overflow

let uniqueHeaderColorArr:[UIColor] = uniqueBackgroundAndHeaderColorArr[1…uniqueBackgroundAndHeaderColorArr.count1]

结果出错:

Cannot subscript a value of type ‘[UIColor]’

搜:

swift Cannot subscript a value of type [UIColor]

ios – Cannot subscript a value of [AnyObject]? with an index of type Int – Stack Overflow

let uniqueHeaderColorArr:[UIColor] = uniqueBackgroundAndHeaderColorArr[1…uniqueBackgroundAndHeaderColorArr.count1] as [UIColor]

错误依旧。

How to get a UIColor from Associative Array in Swift – BlogoSfera

swift subarray

What is a slice in Swift? – Stack Overflow

用Array()的形式,然后再去打印类型:

let uniqueHeaderColorArr:[UIColor] = Array(uniqueBackgroundAndHeaderColorArr[1…uniqueBackgroundAndHeaderColorArr.count1])
print(String(uniqueHeaderColorArr.dynamicType))

即可为:

Array<UIColor>

[总结]

想要获得一个数组的其中一部分子元素作为一个新的数组,可以用:

let newSubArr = Array(originArr[startIdex…endIndex])

即可。

其中:

originArr[startIdex…endIndex]

输出的类型是ArraySlice<ArrayType>

转载请注明:在路上 » [已解决]swift获取一个UIColor数组的部分元素存为新数组

发表我的评论
取消评论

表情

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址
84 queries in 0.168 seconds, using 22.07MB memory