[swift-users] EnumerateUsingObjects in Swift

Doug Hill swiftusers at breaqz.com
Wed Jan 25 12:49:33 CST 2017


OK, I just tried testing this code in my app and a Swift playground. I also tried a variation on the initializer just for the heck of it. I get the following error:

class Test<T>
{
    var array:[T] = []
    var array2 = [T]()

    init() {
        var temp  = self.array as NSArray
        var temp2 = self.array2 as NSArray
    }
}

error: cannot convert value of type '[T]' to type 'NSArray' in coercion
                var temp = self.array as NSArray
                           ~~~~~^
error: cannot convert value of type '[T]' to type 'NSArray' in coercion
                var temp2 = self.array2 as NSArray
                            ~~~~~^

Are there restrictions on what can be converted to NSArray?

Doug Hill

> On Jan 25, 2017, at 9:24 AM, Doug Hill via swift-users <swift-users at swift.org> wrote:
> 
> Thanks for the help. I'm still trying to figure out how Swift works, particularly what the error messages mean. This has been driving me a little nuts trying to figure out what is wrong via sometimes cryptic errors. Also, it seems like getting generic programming working in Swift is more difficult than I'm used to (even than C++!) so this answer helps figure out how the compiler works.
> 
> Doug Hill
> 
> 
>> On Jan 23, 2017, at 7:04 PM, Zhao Xin <owenzx at gmail.com <mailto:owenzx at gmail.com>> wrote:
>> 
>> It seems to me that you didn't initialize your `myArray` before you casted it. That caused the problem.
>> 
>> Zhaoxin
>> 
>> On Tue, Jan 24, 2017 at 9:34 AM, Jon Shier via swift-users <swift-users at swift.org <mailto:swift-users at swift.org>> 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
>>     }
>> }
>> 

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-users/attachments/20170125/47e5bb20/attachment.html>


More information about the swift-users mailing list