斯威夫特:创建具有鲜明的对象实例的默认值数组 [英] Swift: Creating an Array with a Default Value of distinct object instances

查看:233
本文介绍了斯威夫特:创建具有鲜明的对象实例的默认值数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我发现有点怪(和危险恕我直言的)behavoir中的创建一个默认值的数组。正如<一说href=\"https://developer.apple.com/library/$p$prelease/ios/documentation/Swift/Conceptual/Swift_Programming_Language/CollectionTypes.html\"相对=nofollow>雨燕2.1:集合类型

I noticed a bit weird (and dangerous IMHO) behavoir in Creating an Array with a Default Value. As stated in Swift 2.1: Collection Types

斯威夫特的数组类型还提供了与所有设置为相同的默认值的值造成一定大小的数组的初始化。传递这个初始化被添加到新的阵列(称为计数)的项目数和相应的类型的默认值(称为repeatedValue):

Swift’s Array type also provides an initializer for creating an array of a certain size with all of its values set to the same default value. You pass this initializer the number of items to be added to the new array (called count) and a default value of the appropriate type (called repeatedValue):

问题的关键是:相同的默认值;为了了解它是如何工作的,我试图创建这个例子类元素的数组

The point is: same default value; in order to understand how it work, I tried to create an array of elements of this example class

class User {
  private struct Shared {
    static var sequence: Int = 0
  }

  var id: Int
  var thinkTime: NSTimeInterval // typealias di Double

  init (thinkTime: NSTimeInterval) {
    User.Shared.sequence = User.Shared.sequence+1
    id = User.Shared.sequence
    self.thinkTime = thinkTime
  }
}

和这个测试code:

let  howManyUsers: Int = 3
var users = [User](count: howManyUsers, repeatedValue:User(thinkTime: 10.0))
let u2: User = User(thinkTime: 10)
let u3: User = User(thinkTime: 10)
users.append(u2)
users.append(u3)
users[1].thinkTime = 20
users[3].thinkTime = 30

for u in users {
  print("User id:\(u.id) thinktime:\(u.thinkTime)")
}

给出了:

User id:1 thinktime:20.0     
User id:1 thinktime:20.0
User id:1 thinktime:20.0
User id:2 thinktime:30.0
User id:3 thinktime:10.0

这证明明确与要添加到新阵列和相应类型的默认值的项目数初始值设定为:同一个对象实例

that definitively proof the initializer with the number of items to be added to the new array and a default value of the appropriate type are: the same object instance

哪条路,因为简洁和智能成为可能,以获得与初始化的不同的对象实例,具有相同的默认值(不一样的实例,但一些情况下instatiated的数组相同的默认值)?

Which is the way, as concise and smart as possible, to obtain a array of distinct object instances , instatiated with the same default value ( not the same instance but a number of instances initialized with the same default value ) ?

推荐答案

类是引用类型,因此 - 当你发现 - 所有的数组
中元素

Classes are reference types, therefore – as you noticed – all array elements in

var users = [User](count: howManyUsers, repeatedValue:User(thinkTime: 10.0))

引用相同的对象实例(其第一,然后创建
作为参数传递给数组初始化)通过。

reference the same object instance (which is created first and then passed as an argument to the array initializer).

对于结构键入你会得到不同的结果。

For a struct type you would get a different result.

一个可能的解决方案:

var users = (0 ..< howManyUsers).map { _ in User(thinkTime: 10.0) }

在这里,用户实例为每个数组索引创建的。

Here, a User instance is created for each of the array indices.

如果你需要经常那么你可以定义数组初始化
方法,需要一个autoclosure参数:

If you need that frequently then you could define an array init method which takes an "autoclosure" parameter:

extension Array {
    public init(count: Int, @autoclosure elementCreator: () -> Element) {
        self = (0 ..< count).map { _ in elementCreator() }
    }
}

var users = Array(count: howManyUsers, elementCreator: User(thinkTime: 10.0) )

现在第二个参数用户(thinkTime:10.0)被包裹
编译成闭合,并且封闭件对于每个执行
数组索引。

Now the second argument User(thinkTime: 10.0) is wrapped by the compiler into a closure, and the closure is executed for each array index.

这篇关于斯威夫特:创建具有鲜明的对象实例的默认值数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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