init let variable based on a boolean - swift

I use Swift 3 and I want to init a String let variable based on a boolean. I know how to do it with a standard if statement with a var variable but not as a one line expression.
With Java i would do:
String str = myBool ? "John" : "Peter";
Is there a equivalent​ with Swift 3 to not use a var and in a one-line way?

Swift, like Java, supports this ternary operator.
var str = myBool ? "John" : "Peter"

Related

Swift String variable

//First way
var myVar: String = " Hello"
print(myVar)
//Second way
var str = "Hello"
print(str)
I get the same output no matter which of the two I use. What's the difference between them?
These two are basically the same.
When you use var myVar: String = "Hello", you directly tell the swift compiler that your variable is type String.
When you use var myVar = "Hello", you do not specify the type of your variable, so the swift compiler has do do that for you.
Usually, you can get away without declaring your variable type and just have swift do it for you. However, in some cases, namely computed properties and custom classes/structures, you must manually declare your variable to be a specific type.
In your case, either way is fine. The end result is the same, just be aware of the difference for the future.
These two variable are same but with different names :
var myVar
var str
in swift Type doesn't matter that defined because, swift based on value it recognizes what type it is.

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.

difference between two types of variable declarations? [duplicate]

This question already has answers here:
What makes a property a computed property in Swift
(4 answers)
Closed 2 years ago.
I have doubts about where I should use this declaration:
var name: String = 'Name'
and
var name: String = {return 'Name'}
I saw this in some codes where I work, and I would like to know the difference between these statements
TLDR: One is a function, one is a String
var name: String = "Name" is a "regular" variable assignment. You create a var of type String with the identifier name and assign it the value "Name".
var name: String = {return "Name"} won't compile. You're creating a var of type String but then instead of assigning it a string you're assigning it a function. The curly braces indicate a function.
So...
var name = "Name"
print(name)
Creates a variable name with the value name.
Prints the value of variable name [expected output Name]
Whereas
var name = {return "Name"}
print(name)
Creates a variable name with the value of {return "Name"}
Prints that to the console [expected output (Function)]
However
var name = {return "Name"}
print(name())
Creates a variable name with the value of {return "Name"}
Evaluates that function and prints the result [expected output Name]
Therefore
var sum = {return 1+2}
print(sum())
Creates a variable sum with the value of {return 1+2}
Evaluates that function and prints the result [expected output 3]
One last note-- you used single quotes (') but you should declare strings with double quotes (").
The first one is stored property.
The second one is computed property.
The difference here is, the code in { } of computed property is execute each time you access it. It has no memory to store the value by itself.
For example, if your viewController has a property:
var label: UILabel { return UILabel() }
// Then you use it as
label.text = "hello" // label 1
label.textColor = .red // another label, label 2
// the label 1 and label 2 are different, it's initialized each time use access it.

Using DDMathParser to solve string in 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.

How do you use the Optional variable in a ternary conditional operator?

I want to use an Optional variable with the ternary conditional operator but it is throwing error this error: optional cannot be used as boolean. What am I doing wrong?
var str1: String?
var myBool:Bool
myBool = str1 ? true : false
You can not assign string value to bool but You can check it str1 is nil or not like this way :
myBool = str1 != nil ? true : false
print(myBool)
It will print false because str1 is empty.
Nil Coalescing Operator can be used as well.
The code below uses the ternary conditional operator and forced unwrapping (a!) to access the value wrapped inside a when a is not nil, and to return b otherwise
Normal Ternary Operator :
output = a != nil ? a! : b
Apple Developer Link : Please refer to Demo Link
In Swift 1.2 & 2, above line of code is replaced by a shorter format:
output = a ?? b
Demo Link : The nil coalescing operator (a ?? b) unwraps an optional a if it contains a value, or returns a default value b if a is nil.
This even works well if the value you want is a property or result of a function call on an optional (in Swift 3.0):
return peripheral?.connected ?? false
Ternary operators operate on three targets. Like C, Swift has only one
ternary operator, the ternary conditional operator (a ? b : c).
Example usage on tableView -
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return section == 2 ? 4 : 1
}
indicates if section equal to 2 then it return 4 otherwise 1 on false.
To add on the already very good answers, sometimes you need the convenience of the ternary operator but also need to perform changes on the wrapped value, such as;
var fullName = lastName != nil ? "\(firsName) \(lasName!)" : firstName
But you don't want to force unwrap (even though this situation would be fine).
Then you can actually use Optional.map:
var fullName = lastName.map({ "\(firstName) \($0)" }) ?? firstName
The completion block passed to .map is only called if the wrapped value ($0) is not nil. Otherwise, that function just returns nil, which you can then easily coalesce with the ?? operator.
In case the comparison is based on some condition
let sliderValue = Float(self.preferenceData.getLocationRadius().characters.count > 1 ?self.preferenceData.getLocationRadius():"0.1")
Here the function getLocationRadius() returns a String. One more thing if we don't put a space between 1 and ? it results in an syntax error