5
\$\begingroup\$

I'm using Swift 2.1 and ReactiveCocoa 4.0.4 alpha 1. I'm combining multiple signals to enable a button based on if they have valid inputs. The following code works correctly, but I'm wondering if there is a more elegant and efficient way of accomplishing this with the ReactiveCocoa APIs, as well as if this is the proper way to be using the API in Swift.

 let sig0 = firstTextField.rac_textSignal()
 .max(self.firstTextField, max: maxLength)
 .map{ next in
 if let str = next as? String {
 return str.characters.count > 0
 } else {
 return false
 }
 }
 let sig1 = secondTextField.rac_textSignal()
 .max(self.secondTextField, max: maxLength)
 .map{ next in
 if let str = next as? String {
 return str.characters.count > 0
 } else {
 return false
 }
 }
 let combined = RACSignal.combineLatest([sig0, sig1])
 combined.subscribeNext { (obj: AnyObject!) -> Void in
 let tup = obj as! RACTuple
 let valid = (tup.first as! Bool) && (tup.second as! Bool)
 self.button.enabled = valid
 }
asked Nov 8, 2015 at 19:15
\$\endgroup\$
0

1 Answer 1

2
\$\begingroup\$

I'm familiar with RxSwift, not RAC. :-( That said, I think I can say something constructive about this code...

sig0 and sig1 need more descriptive names.

I would be inclined to break up the combined.subscribeNext function. Something more like:

let buttonEnabled = RACSignal.combineLatest([sig0, sig1])
 .map { obj in 
 let tup = obj as! RACTuple // Wow RAC doesn't return type safe values?
 return (tup.first as! Bool) && (tup.second as! Bool)
 }
buttonEnabled.subscribeNext { obj in 
 let valid = obj as! Bool
 self.button.enabled = valid 
}

I strongly suspect that there is a function for mapping the buttonEnabled signal directly to the button though, maybe with an Action? You should look into that.

answered Apr 2, 2016 at 18:47
\$\endgroup\$
1
  • \$\begingroup\$ This looks like a good solution, thanks! I've actually moved to RxSwift since this question because I found it to work much better with Swift \$\endgroup\$ Commented Apr 2, 2016 at 23:35

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.