[swift-users] EnumerateUsingObjects in Swift
Doug Hill
swiftusers at breaqz.com
Wed Jan 25 11:27:23 CST 2017
Thanks for the tip about 'concurrentPerform'!
> On Jan 23, 2017, at 5:34 PM, Jon Shier <jon at jonshier.com> wrote:
>
> enumerateObjects(options:using:) exists on NSArray in Swift. And I was able to create your generic class just fine:
>
> class Test<T> {
> var array: [T] = []
>
> init() {
> var temp = array as NSArray
> }
> }
>
> I’m not sure what the canonical parallel array enumeration would be, but you can do it using concurrentPerform:
>
> let array = [“one”, “two”]
> DispatchQueue.concurrentPerform(iterations: array.count) { index in
> print(array[index])
> }
>
>
>> On Jan 23, 2017, at 8:20 PM, Doug Hill via swift-users <swift-users at swift.org <mailto:swift-users at swift.org>> wrote:
>>
>> I'm trying to accomplish the equivalent functionality of -[NSArray enumerateUsingObjects:…] in Swift. Doing a Googles search, I see that one would need to call the equivalent method on the bridged NSArray version of your Swift array:
>>
>> var myNSArray : NSArray = mySwiftArray as NSArray
>>
>> Here's the problem I'm running into; I have the following class:
>>
>> class Tester<typeA>
>> {
>> var myArray : [typeA]
>>
>> init()
>> {
>> var temp = self. myArray as NSArray
>> }
>> }
>>
>> Which produces a compiler error:
>>
>> 'cannot convert value of type '[typeA]' to type 'NSArray' in coercion'
>>
>> Ok, this makes some sense since I'm guessing NSArray requires each element to to be an NSObject but this array type Array<typeA> could be a non-NSObject.
>>
>> However, this makes my code harder to write since I now have to make sure any array has element type NSObject to use enumerateUsingObjects. Not something I can either guarantee or even desire.
>>
>> The reason I like enumerateUsingObjects is that it supports a functional style of programming and is better at creating work items for each object by dispatching each array item on multiple cores/processors/threads for me. Writing this method myself would require figuring out to pass an object to a dispatch invocation. But looking through the swift API's, I don't see any GCD method for passing an object to dispatch_sync/async. I see versions of these methods that takes a context parameter but then takes a C function instead of a block, so not very Swift-like and potentially unsafe.
>>
>> Does this mean enumerateUsingObjects is generally not all that useful in Swift? Are there better alternatives? Any ideas on how best to handle this situation would be appreciated.
>>
>> Doug Hill
>> _______________________________________________
>> swift-users mailing list
>> swift-users at swift.org <mailto:swift-users at swift.org>
>> https://lists.swift.org/mailman/listinfo/swift-users
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-users/attachments/20170125/d35dd82e/attachment.html>
More information about the swift-users
mailing list