xcode - Differences between Playground and Project -


in course of answering question, came across weird bug in playground. have following code test if object array, dictionary or set:

import foundation  func iscollectiontype(value : anyobject) -> bool {     let object = value as! nsobject      return object.iskindofclass(nsarray)         || object.iskindofclass(nsdictionary)         || object.iskindofclass(nsset) }  var arrayofint = [1, 2, 3] var dictionary = ["name": "john", "age": "30"] var anint      = 42 var astring    = "hello world"  println(iscollectiontype(arrayofint)) // true println(iscollectiontype(dictionary)) // true println(iscollectiontype(anint))      // false println(iscollectiontype(astring))    // false 

the code worked expected when put swift project or running command line. playground wouldn't compile , give me following error on downcast nsobject:

playground execution failed: execution interrupted, reason: exc_bad_access (code=2, address=0x7fb1d0f77fe8). * thread #1: tid = 0x298023, 0x00007fb1d0f77fe8, queue = 'com.apple.main-thread', stop reason = exc_bad_access (code=2, address=0x7fb1d0f77fe8)   * frame #0: 0x00007fb1d0f77fe8     frame #1: 0x000000010ba46e12 libswiftcore.dylib`swift._emptyarraystorage._withverbatimbridgedunsafebuffer (swift._emptyarraystorage)<a>((swift.unsafebufferpointer<swift.anyobject>) -> a) -> swift.optional<a> + 50 

the build platform os x in 3 cases. know how playground play along?

xcode 6.3.2. swift 1.2. os x 10.10.3 yosemite

not cause of bug (it weird) but... need use optional chaining since value can anyobject:

import foundation  func iscollectiontype(value : anyobject) -> bool {     if let object = value as? nsobject {         return object.iskindofclass(nsarray)             || object.iskindofclass(nsdictionary)             || object.iskindofclass(nsset)         }     return false }  var arrayofint = [1, 2, 3] var dictionary = ["name": "john", "age": "30"] var anint      = 42 var astring    = "hello world"  iscollectiontype(arrayofint) iscollectiontype(dictionary) iscollectiontype(anint) iscollectiontype(astring) 

playground

also worth noting, nsarray , array different things:

  • nsarray immutable class:

    @interface nsarray : nsobject <nscopying, nsmutablecopying, nssecurecoding, nsfastenumeration>

  • whilst array struct:

    struct array<t> : mutablecollectiontype, sliceable, _destructorsafecontainer

with in mind might surprising iscollectiontype(arrayofint) returns true - there conversion happening.


Comments

Popular posts from this blog

c# - Validate object ID from GET to POST -

node.js - Custom Model Validator SailsJS -

php - Find a regex to take part of Email -