Reducing the number of brackets in Swift - swift

Does anyone know if there is a way to use some kind shorthand in swift? more specifically, leaving out the braces in things like IF statements... eg
if num == 0
// Do something
instead of
if num == 0
{
// Do something
}
Those braces become rather space consuming when you have a few nested IF's.
PS. I do know I can do the following:
if num == 0 {
// Do something }
But I'm still curious if that sort of thing is possible

You can do that :
let x = 10, y = 20;
let max = (x < y) ? y : x ; // So max = 20
And so much interesting things :
let max = (x < y) ? "y is greater than x" : "x is greater than y" // max = "y is greater than x"
let max = (x < y) ? true : false // max = true
let max = (x > y) ? func() : anotherFunc() // max = anotherFunc()
(x < y) ? func() : anotherFunc() // code is running func()
This following stack : http://codereview.stackexchange.com can be better for your question ;)
Edit : ternary operators and compilation
By doing nothing more than replacing the ternary operator with an if else statement, the build time was reduced by 92.9%.
https://medium.com/#RobertGummesson/regarding-swift-build-time-optimizations-fc92cdd91e31#.42uncapwc

In swift you have to add braces even if there is just one statement in if:
if num == 0 {
// Do something
}
You cannot leave the braces, that how swift if statement work.

You could use a shorthand if statement like you would in objective-c:
num1 < num2 ? DO SOMETHING IF TRUE : DO SOMETHING IF FALSE

Swift 2.0 update
Method 1:
a != nil ? a! : b
Method 2: Shorthand if
b = a ?? ""
Referance: Apple Docs: Ternary Conditional Operator
and it does work,
u.dob = (userInfo["dob"] as? String) != nil ? (userInfo["dob"] as! String):""
I am replacing a json string with blank string if it is nil.
Edit: Adding Gerardo Medina`s suggestion...we can always use shorthand If
u.dob = userInfo["dob"] as? String ?? ""

It is called shorthand if-else condition. If you are into iOS development in Swift, then you can also manipulate your UI objects' behaviour with this property.
For e.g. - I want my button to be enabled only when there is some text in the textfield. In other words, should stay disabled when character count in textfield is zero.
button.enabled = (textField.characters.count > 0) ? true : false

its very simple :
in Swift 4
playButton.currentTitle == "Play" ? startPlay() : stopPlay()
Original Code is
if playButton.currentTitle == "Play"{
StartPlay()
}else{
StopPlay()
}

You could always put the entire if on one line:
if num == 0 { temp = 0 }

Related

swift: about ternary operator Question. Why my code is error code??? Please tell me why I'm wrong

swift: about ternary operator Question. Why my code is error code??? Please tell me why I'm wrong.
var arr = [0,1,2,3,4,5,6,7,8]
var result = 0;
for a in 0..<arr.count{
for b in 1..<arr.count - 1{
for c in 2..<arr.count - 2 {
arr[a] + arr[b] + arr[c] <= input[1] ? result = arr[a] + arr[b] +arr[c] : continue
}
}
}
[this is my error]
[1]: https://i.stack.imgur.com/UdiUB.png
In Swift, the ternary condition operator is an expression which takes the form
<condition> ? <expression if true> : <expression if false>
Expressions are part of larger statements, and the ternary specifically is one which evaluates to either the expression after the ?, or the one after the : depending on the truth of the condition.
continue, however, is not an expression but a statement on its own, which means that it cannot be on either side of the ternary.
Thinking about this another way: expressions evaluate to some value (e.g., can be put on the right-hand-side of an assignment, like x = <some expression>), while statements do not (e.g., it doesn't make sense to write x = continue).
You will need to express this in the form of a regular if-statement then:
if arr[a] + arr[b] + arr[c] <= input[1] {
result = arr[a] + arr[b] +arr[c]
} else {
continue
}
Note that the above code might be grammatically correct (in that it will compile), but it is unlikely to be what you mean: the loop will automatically continue at the end of execution even if arr[a] + arr[b] + arr[c] <= input[1] by default, which means that your result may get overwritten later in the loop. It seems likely that you mean something like
outer_loop: for a in 0 ..< arr.count {
for b in 1 ..< arr.count - 1 {
for c in 2 ..< arr.count - 2 {
if arr[a] + arr[b] + arr[c] <= input[1] {
result = arr[a] + arr[b] + arr[c]
// `break` would only exit the `c` loop, but with this label
// we can exit all loops at once.
break outer_loop
}
}
}
}

Can i compare two bytes values on basis of nearly equal to in swift

i have two values in bytes in two different variables . i want to perform a certain action whenever values are nearly equal to each other.
I there any method in swift in which i can perform any action on variables values nearly equal to.
If recommend me some code , tutorial or article to achieve this.
I am new to swift so please avoid down voting.
let string1 = "Hello World"
let string2 = "Hello"
let byteArrayOfString1: [UInt8] = string1.utf8.map{UInt8($0)} //Converting HELLO WORLD into Byte Type Array
let byteArrayOfString2: [UInt8] = string2.utf8.map{UInt8($0)} //Converting HELLO into Byte Type Array
if byteArrayOfString1 == byteArrayOfString2 {
print("Match")
}else {
print("Not Match")
}
For more Help, Visit https://medium.com/#gorjanshukov/working-with-bytes-in-ios-swift-4-de316a389a0c
well exactly i don't think so there is such method that compare approx values but if you discuss what exactly you want to do we can find a better alternative solution.
Here is the Solution:
func nearlyEqual(a: Float, b: Float, epsilon: Float) -> Bool {
let absA = abs(a)
let absB = abs(b)
let diff = abs(a - b)
if a == b {
return true
} else if (a == 0 || b == 0 || absA + absB < Float.leastNonzeroMagnitude) {
// a or b is zero or both are extremely close to it
// relative error is less meaningful here
return diff < (epsilon * Float.leastNonzeroMagnitude)
} else {
return diff / (absA + absB) < epsilon
}
}
Then you can use it like :
print(nearlyEqual(a: 1.2, b: 1.4, epsilon: 0.2))
This will return true.

How to check if a number is a power of 2 in SWIFT

I find out a lot of example to solve it, but nothing in SWIFT. Please help
smthng like this
Input : n = 4
Output : Yes
2^2 = 4
Input : n = 7
Output : No
Input : n = 32
Output : Yes
2^5 = 32
I needed algorithm for checking if a number is a power of 2. like 4, 8, 16 , 32 , 64 .... is number power of two
Determining if an integer is a power of 2
from the Bit Twiddling Hacks
is almost verbatim translated to Swift:
func isPowerOfTwo(_ n: Int) -> Bool {
return (n > 0) && (n & (n - 1) == 0)
}
Example:
print(isPowerOfTwo(4)) // true
print(isPowerOfTwo(5)) // false
Or as a generic function, so that it can be used with all binary
integer types:
func isPowerOfTwo<T: BinaryInteger> (_ n: T) -> Bool {
return (n > 0) && (n & (n - 1) == 0)
}
Example:
print(isPowerOfTwo(Int16(4))) // true
print(isPowerOfTwo(UInt8(5))) // false
Or as a protocol extension:
extension BinaryInteger {
var isPowerOfTwo: Bool {
return (self > 0) && (self & (self - 1) == 0)
}
}
Example:
print(1048576.isPowerOfTwo) // true
print(Int(50).isPowerOfTwo) // false
Partial answer:
If it's a FixedWidthInteger and it's positive and its non zero bit count is 1, then it is a power of 2.
let x = 128
if x > 0 && x.nonzeroBitCount == 1
{
// power of 2
}
For a floating point number, I think you can just test the significand. If it is exactly 1, the number is a power of 2.
let x: Double = 4
if x > 0 && x.significand == 1
{
// Power of 2
}
I haven't checked that in a Playground yet, so it might be wrong.
let numberToBeChecked = 4
result = numberToBeChecked.squareRoot()
If result%1 == 0 {
print(“4 is a power of 2”) } else {
print(“4 is not a power of 2”)
}
//note: result%1== 0 checks if result is a whole number.
Hope this works.

What does arc4random_uniform() do in a conditional?

This code passes 3 as an argument to the arc4random_uniform() function and I guess that it returns true or false. Next you assign an enumerator to a variable. I don't understand what the function does, though.
let randomState = arc4random_uniform(3) == 2 ? CellState.Alive :
CellState.Empty
let cell = Cell(grid: self,
pos: (i, j),
state: randomState)
I am not following that logic.
Is it the "arc4random_uniform(3) == 2 ? CellState.Alive : CellState.Empty" format that you don't understand? It's written as a conditional (ternary) operator:
condition ? expr1 : expr2
Basically, if func arc4random_uniform(3) == 2, let randomState == CellState.Alive, otherwise let randomState == CellState.Empty.

Add an "s" to the end of a string, depending on a variable

I'd like to append an s to the end of a string, if the value of a variable is > 1.
There are obviously several ways to accomplish this - for example:
if(points == 1) {
points_as_string = "1 Point"
} else {
points_as_string = "\(points) Points"
}
A shorter version could be:
points_as_string = (points == 1 ? "1 Point" : "\(points) Points")
An even shorter version would be:
points_as_string = "\(points) Point" + (points == 1 ? "" : "s")
Is it possible to write something even shorter than that, or is that as good as it gets?
Only very slightly shorter:
points_as_string = "\(points) Point\(points == 1 ? "" : "s")"
Here is a shorter version that uses a dictionary lookup and the nil coalescing operator ??:
points_as_string = "\(points) Point\([1:""][points] ?? "s")"