3

OMG, for the life of me I can't get this to work.

  • I've got a typdef in objective-c that looks like this:
typedef void (^StringBlock)(NSString * string);
  • I've got an objective-c class that has a property that allows you to store your own block of StringBlock type. That property is declared in objective-c like this:
@property (nonatomic, copy) StringBlock onTextSubmitBlock;
  • Assigning a block to it in objective-c looks like this:
input.onTextSubmitBlock = ^(NSString * text) {

};
  • I want to do the same thing from within a Swift class! The closest I've come to having something that works is this:
input!.onTextSubmitBlock = {(StringBlock) in

}

That compiles, but I have no access to the argument I need ((NSString * text) in objective-c...)

I'm sure that once I get used to Swift this will be obvious, but what am I missing?

shmim
  • 729
  • 9
  • 21

1 Answers1

2

You are pretty close. You should be able to use it like this:

input!.onTextSubmitBlock = { text in
    println(text)
}

Swift will infer that text is an NSString from the declaration. Thera are a couple alternative ways you could declare this as well. Like this:

input!.onTextSubmitBlock = {
    println($0) // $0 is text
}

And this:

input!.onTextSubmitBlock = { (text: NSString) -> () in
    println(text)
}
Ben Kane
  • 9,331
  • 6
  • 36
  • 58
  • Yes! That's so beautifully simple. But why would: `input!.onTextSubmitBlock = { (text:NSString) in` fail? – shmim Mar 19 '15 at 18:07
  • You can do it that way, but you'd have to include the return type as well, like this: `input!.onTextSubmitBlock = { (text: NSString) -> () in` – Ben Kane Mar 19 '15 at 18:19
  • 1
    Nicely done. Thanks! However, the compiler still complains about `input!.onTextSubmitBlock = { (text: NSString) -> () in`, saying `Cannot assign a value of type '(NSString) -> ()' to a value of type 'StringBlock!'` – shmim Mar 19 '15 at 18:55
  • Sorry for continued noobishness... Swift is weird. I'm using this: `input!.onTextSubmitBlock = { text in` but if text is nil, program crashes with `unexpectedly found nil while unwrapping an Optional values`. It seems I can't deal with this using `let` or `!` or `?`, which are the only options I can think of... – shmim Mar 19 '15 at 19:07
  • 1
    Since you declared the block in Objective-C, it's being imported to swift as an implicitly unwrapped optional (Autocomplete would show it as `NSString!`). If you're running an Xcode 6.3 Beta you'll be able to add either __nullable or __nonnull to your Objective-C block (see [here](https://developer.apple.com/swift/blog/?id=25) for an explanation. e.g. You could declare it as __nullable in Objective-C, and it'll become `NSString?` in Swift. __nonnull will become `NSString`. If you're not on the betas you will just have to wait for that feature. – Ben Kane Mar 19 '15 at 19:15
  • Either way, if it can be null you'll need an `if let`. – Ben Kane Mar 19 '15 at 19:16