ios - why does swift dictionary with function work outside of a class but produces error inside of a class? -
i came across issue (and playground able locate it)
i seek utilize dictionary, has numbers keys , functions values. works fine outside of class:
private func hello1(x: double) { println("hello1") } private func hello2(x: double) { println("hello2") } private allow contacts: [int: double -> ()] = [ 0 : hello1, 1 : hello2 ] contacts[1]?(1.0) // works fine :-)
when set identical code within class, compiler error
'double' not subtype of 'someclass'
with identical code:
internal class someclass { private func hello1(x: double) { println("hello1") } private func hello2(x: double) { println("hello2") } private allow contacts: [int: double -> ()] = [ // *** here error *** 0 : hello1, 1 : hello2 ] internal func runit() { contacts[1]?(1.0) } } allow someclass = someclass() someclass.runit()
i tried several ways of brackets. no improvements.
what did missed when learning swift? did misunderstand or misinterpret?
hello1
, hello2
instance method. if referenced someclass.hello1
, type someclass -> (double) -> ()
. can phone call this:
var foo = someclass() someclass.hello1(foo)(1.0)
it's curried function. , why got error 'double' not subtype of 'someclass'
.
if want want, should this:
internal class someclass { private func hello1(x: double) { println("hello1") } private func hello2(x: double) { println("hello2") } lazy private var contacts: [int: double -> ()] = [ 0 : self.hello1, 1 : self.hello2 ] internal func runit() { contacts[1]?(1.0) } }
you have utilize lazy var
instead of let
, or cannot reference self
.
added:
above code makes strong reference cycles. should utilize closures [unowned self]
.
lazy private var contacts: [int: double -> ()] = [ 0 : {[unowned self] in self.hello1($0) }, 1 : {[unowned self] in self.hello2($0) } ]
ios xcode osx swift
No comments:
Post a Comment