Using DDMathParser to solve string in swift - swift

I want to pass a string to DDMathParser and store answer in another string variable using swift. I am totally new to iOS platform so I dont really know syntax of functions. Example:
var expr = "5+9*2" //Some Expression
var result = DDMathParser.evaluate(expr) // Result of Expression

Here is a simple example how to use DDMathParser from Swift:
let expr = "5+9*2" as NSString
let result = expr.numberByEvaluatingString().integerValue
println(result) // 23
If you need floating point results then replace integerValue
by doubleValue.

Related

what is the best way to write this function? [duplicate]

just a short question. In Swift it is possible to solve the following code:
var a: String;
a = "\(3*3)";
The arithmetic operation in the string will be solved. But i can´t figure out, why this following variation doesn´t work.
var a: String;
var b: String;
b = "3*3";
a = "\(b)";
In this case the arithmetic operation in var a will not be resolved. Any ideas why and how i can this get to work. Some things would be much more easier if this would work. Thanks for your answers.
In the second case, you are interpolating a string, not an arithmetic expression. In your example, it's a string you chose at compile time, but in general it might be a string from the user, or loaded from a file or over the web. In other words, at runtime b could contain some arbitrary string. The compiler isn't available at runtime to parse an arbitrary string as arithmetic.
If you want to evaluate an arbitrary string as an arithmetic formula at runtime, you can use NSExpression. Here's a very simple example:
let expn = NSExpression(format:"3+3")
println(expn.expressionValueWithObject(nil, context: nil))
// output: 6
You can also use a third-party library like DDMathParser.
Swift 4.2
let expn = "3+3"
print(expn.expressionValue(with: nil, context: nil))
But I also have a solution thats not the most effective way but could be used in some cases if your sure it's only "y+x" and not longer string.
var yNumber: Int!
var xNumber: Int!
let expn: String? = "3+3"
// Here we take to first value in the expn String.
if let firstNumber = expo?.prefix(1), let myInt = Int(firstNumber){
// This will print (Int : 3)
print("Int : \(myInt)")
// I set the value to yNumber
yNumber = myInt
}
// Here we take the last value in the expn string
if let lastNumber = optionalString?.suffix(1), let myInt = Int(lastNumber){
// This will print (Int : 3)
print("Int : \(myInt)")
// I set the value to xNumber
xNumber = myInt
}
// Now you can take the two numbers and add
print(yNumber + xNumber)
// will print (6)
I can't recommend this but it works in some cases
This won't be solved because this is not an arithmetic operation, this is a string:
"3*3"
the same as this
"String"
Everything you put in " it's a string.
The second example lets you construct a new String value from a mix of constants, variables, literals, and expressions:
"\(3*3)"
this is possible because of string interpolation \()
You inserted a string expression which swing convert and create expected result.
You can try to use evaluatePostfixNotationString method from that class.
The whole project is about recognizing math expression from camera image and calculating it after.

How to initialize a unichar variable in swift?

I have a function that requires a unichar parameter. But could not find a nice way to initialize a unichar in swift.
I am using the following way:
var delimitedBy:unichar = ("," as NSString).characterAtIndex(0)
Is there a better way to initialize a unichar in swift?
Swift can infer the type and you don't need to cast the String literal to NSString:
var delimitedBy = ",".characterAtIndex(0)
Another possible solution:
var delimitedBy = first(",".utf16)!
(Note that unichar is a type alias for UInt16). This works also
with string variables (which of course should not be the empty string).
Update for Swift 2/Xcode 7:
var delimitedBy = ",".utf16.first!
Swift 5 would be:
let delimeter = ",".utf16.first!

Swift - Resolving a math operation in a string

just a short question. In Swift it is possible to solve the following code:
var a: String;
a = "\(3*3)";
The arithmetic operation in the string will be solved. But i can´t figure out, why this following variation doesn´t work.
var a: String;
var b: String;
b = "3*3";
a = "\(b)";
In this case the arithmetic operation in var a will not be resolved. Any ideas why and how i can this get to work. Some things would be much more easier if this would work. Thanks for your answers.
In the second case, you are interpolating a string, not an arithmetic expression. In your example, it's a string you chose at compile time, but in general it might be a string from the user, or loaded from a file or over the web. In other words, at runtime b could contain some arbitrary string. The compiler isn't available at runtime to parse an arbitrary string as arithmetic.
If you want to evaluate an arbitrary string as an arithmetic formula at runtime, you can use NSExpression. Here's a very simple example:
let expn = NSExpression(format:"3+3")
println(expn.expressionValueWithObject(nil, context: nil))
// output: 6
You can also use a third-party library like DDMathParser.
Swift 4.2
let expn = "3+3"
print(expn.expressionValue(with: nil, context: nil))
But I also have a solution thats not the most effective way but could be used in some cases if your sure it's only "y+x" and not longer string.
var yNumber: Int!
var xNumber: Int!
let expn: String? = "3+3"
// Here we take to first value in the expn String.
if let firstNumber = expo?.prefix(1), let myInt = Int(firstNumber){
// This will print (Int : 3)
print("Int : \(myInt)")
// I set the value to yNumber
yNumber = myInt
}
// Here we take the last value in the expn string
if let lastNumber = optionalString?.suffix(1), let myInt = Int(lastNumber){
// This will print (Int : 3)
print("Int : \(myInt)")
// I set the value to xNumber
xNumber = myInt
}
// Now you can take the two numbers and add
print(yNumber + xNumber)
// will print (6)
I can't recommend this but it works in some cases
This won't be solved because this is not an arithmetic operation, this is a string:
"3*3"
the same as this
"String"
Everything you put in " it's a string.
The second example lets you construct a new String value from a mix of constants, variables, literals, and expressions:
"\(3*3)"
this is possible because of string interpolation \()
You inserted a string expression which swing convert and create expected result.
You can try to use evaluatePostfixNotationString method from that class.
The whole project is about recognizing math expression from camera image and calculating it after.

Working with C strings in Swift, or: How to convert UnsafePointer<CChar> to CString

While playing with Standard C Library functions in Swift, I came across problems
when passing C strings around. As a simple example (just to demonstrate the problem), the Standard C Library function
char * strdup(const char *s1);
is exposed to Swift as
func strdup(_: CString) -> UnsafePointer<CChar>
which means that the return value of strdup() cannot be passed to another strdup() call:
let s1 : CString = "abc"
let s2 = strdup(s1) // OK, s2 is a UnsafePointer<CChar>
let s3 = strdup(s2) // error: could not find an overload for '__conversion' that accepts the supplied arguments
My question is: How to create a Swift CString from a UnsafePointer<CChar>,
so that the C string returned by one standard library function can be passed to another function?
The only way that I could find is (using code from How do you convert a String to a CString in the Swift Language?):
let s2a = String.fromCString(s2).bridgeToObjectiveC().UTF8String
let s3 = strdup(s2a)
But I do not find this satisfying for two reasons:
It is too complicated for a simple task.
(Main reason:) The above conversions works only if the C string is a valid UTF-8
string, otherwise it fails with a runtime exception. But a C string is an arbitrary
sequence of characters, delimited by a NUL character.
Remarks/Background: Of course, high-level functions using high-level data structures like Swift String or Objective-C NSString are preferable. But there are BSD functions in the
Standard C Library which do not have an exact counterpart in the Foundation frameworks.
I came across this problem while trying to answer Accessing temp directory in Swift.
Here, mkdtemp() is a BSD function for which no exact NSFileManager replacement exists
(as far as I know).
mkdtemp() returns a UnsafePointer<CChar> which has to be passed to the
NSFileManager function stringWithFileSystemRepresentation which takes a CString
argument.
Update: As of Xcode 6 beta 6, this problem does not exist anymore because the mapping of C-Strings into Swift has been simplified. You can just write
let s1 = "abc" // String
let s2 = strdup(s1) // UnsafeMutablePointer<Int8>
let s3 = strdup(s2) // UnsafeMutablePointer<Int8>
let s4 = String.fromCString(s3) // String
Swift 1.1 (or perhaps earlier) has even better C string bridging:
let haystack = "This is a simple string"
let needle = "simple"
let result = String.fromCString(strstr(haystack, needle))
The CString type is gone completely.
The String struct in Swift has an init routine you can use like:
let myString = String(cString: myUnsafePointer)
see also init(cString: UnsafePointer)

How do you convert a String to a CString in the Swift Language?

I am trying to use dispatch_queue_create with a dynamic String that I am creating at runtime as the first parameter. The compiler complains because it expects a standard c string. If I switch this to a compile time defined string the error goes away. Can anyone tell me how to convert a String to a standard c string?
You can get a CString as follows:
import Foundation
var str = "Hello, World"
var cstr = str.bridgeToObjectiveC().UTF8String
EDIT: Beta 5 Update - bridgeToObjectiveC() no longer exists (thanks #Sam):
var cstr = (str as NSString).UTF8String
There is also String.withCString() which might be more appropriate, depending on your use case. Sample:
var buf = in_addr()
let s = "17.172.224.47"
s.withCString { cs in inet_pton(AF_INET, cs, &buf) }
Update Swift 2.2: Swift 2.2 automagically bridges String's to C strings, so the above sample is now a simple:
var buf = in_addr()
let s = "17.172.224.47"
net_pton(AF_INET, s, &buf)
Much easier ;->
Swift bridges String and NSString. I believe this may be possible alternative to Cezary's answer:
import Foundation
var str = "Hello World"
var cstr = str.cStringUsingEncoding(NSUTF8StringEncoding)
The API documentation:
/* Methods to convert NSString to a NULL-terminated cString using the specified
encoding. Note, these are the "new" cString methods, and are not deprecated
like the older cString methods which do not take encoding arguments.
*/
func cStringUsingEncoding(encoding: UInt) -> CString // "Autoreleased"; NULL return if encoding conversion not possible; for performance reasons, lifetime of this should not be considered longer than the lifetime of the receiving string (if the receiver string is freed, this might go invalid then, before the end of the autorelease scope)
Swift 3 version as #mbeaty's say:
import Foundation
var str = "Hello World"
var cstr = str.cString(using: String.Encoding.utf8)
Apple API:
Foundation > String > cString(using:)
Instance Method
cString(using:)
Returns a representation of the String as a C string using a given encoding.
Swift 5
var cstr = (userStr as NSString).utf8String
Swift 5
Remember to guarantee the lifetime, like:
let myVariable: String = "some text...";
withExtendedLifetime(myVariable) {
myVariable.utf8CString.withUnsafeBufferPointer { buffer in
let result = buffer.baseAddress!;
// ... Do something with result
}
}