Search code examples
cocoaswiftenterevaluate

Swift Programming: Evaluate value in a string


My question is on SWIFT/COCOA programming. I want to evaluate the content inside a string. For example, I have var1 = "2 + 3" Is there any inbuilt function in SWIFT/COCOA that can evaluate content in var1 and return 5. I tried what I could understand from string interpolation but that is not helping

var myNum = "45/30"
var myNum2 = "sin(30)"
var myNum3 = "\(Float(myNum) * Float(myNum2))";

error: could not find member 'convertFromStringInterpolationSegment'

Also, got another question.. How do I detect Return key pressed in SWIFT? Any trigger similar to "func applicationWillTerminate(aNotification: NSNotification) "


Solution

  • For your second question, assuming you're using a textField, you can use the delegate method:

    - (BOOL)textFieldShouldReturn:(UITextField *)textField
    

    This method is executed when the return key is pressed. If don't want to hide the keyboard, you need to return NO from this function at the end.


    If you're using a textView, you can refer to this thread. You implement the textView:shouldChangeTextInRange:replacementText: method of UITextViewDelegate and in that check if the replacement text is \n.