Reducing the Number of Brackets in Swift

Reducing the number of brackets in Swift

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

Reducing the number of brackets in Swift

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

How to remove all values within square brackets, including the brackets | Swift

you could try something simple like this:

var sampleString = "[2049A30-3930Q4] The Rest of the String"

sampleString.removeSubrange(sampleString.startIndex..."[2049A30-3930Q4]".endIndex)
// this will also work
// sampleString.removeSubrange(sampleString.startIndex..."[0000000-000000]".endIndex)
print("----> sampleString: \(sampleString)")


EDIT-1: more general approach if needed.

if let from = sampleString.range(of: "[")?.lowerBound,
let to = sampleString.range(of: "]")?.upperBound {
sampleString.removeSubrange(from...to)
print("----> sampleString: \(sampleString)")
}

Need to check that braces in given array are balanced or not

import Foundation

extension String {

func isBalanced() -> Bool {
switch self.filter("()[]{}".contains)
.replacingOccurrences(of: "()", with: "")
.replacingOccurrences(of: "[]", with: "")
.replacingOccurrences(of: "{}", with: "") {
case "": return true
case self: return false
case let next: return next.isBalanced()
}
}

}

To explain:

  1. filter("()[]{}".contains) removes any characters except the delimiters. It means the same as filter({ c in "()[]{}".contains(c) }).

  2. Any finite-length, non-empty balanced string must contain one or more empty delimiter pairs ((), [], or {}). Deleting all empty pairs doesn't change the balanced-ness of the string. So delete any such empty pairs using replacingOccurrences(of:with:).

  3. If, after deleting all empty pairs, you have an empty string, then you started with a balanced string, so return true.

  4. If, after deleting all empty pairs, you didn't actually remove any empty pairs (and you don't have an empty string), then you must have an unbalanced delimiter, so return false.

  5. If, after deleting all empty pairs, you removed at least one pair, then you might now have new empty pairs. For example, deleting the empty pairs of [({})][({})] gives [()][()], which has new empty pairs. So try to do more deleting by calling isBalanced tail-recursively.

Are all brackets for if-statements and loops in Swift optional?

If you look at the language syntax, the if statement is defined like this:

if *expression* {

and you can always add parenthesis around expressions.

However, for-in is defined as:

for *item* in *collection expression* {

You can still add parenthesis around the expression. However, you cannot put parenthesis around the keyword in.

Divide String in Swift by Brackets

If you replace in source string braces "{}" with square braces "[]" the source become a valid Json - array with 2 elements, each element is an array with 3 values - than you can parse it using NSJSONSerialization:

var source = "{{\"1\", \"test.pdf\", 495207}, {\"2\", \"test2.ics\", 972}}"
var string = source.stringByReplacingOccurrencesOfString("{", withString: "[")
string = string.stringByReplacingOccurrencesOfString("}", withString: "]")

let data = string.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: true)
let json = NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.allZeros, error: nil) as? [AnyObject]

var objects: [MyClass] = []

if let array = json {
for element in array {
let array = element as! [AnyObject]
let id = array[0] as! String
let filename = array[1] as! String
let number = array[2] as! UInt
objects.append(MyClass(id: id, filename: filename, number: number))
}
}

Swift: Multiplication and brackets calculation doesn't work

This should work:

let numerator: Double = (5-2) * (10-5)
let denumerator: Double = (4-2) * (10-5)

Fist you calculate the numerator and denumerator. And finally the result:

print(result)
let result: Double = numerator/denumerator
//1.5

Swift 4: Formatting number's into friendly K's

This answer formats by truncating (versus rounding). 1,515 rounded would generate 2k whereas truncated would generate 1.5k. The function requires reducing a number's scale (removing digits to the right of the decimal) which I've just packaged as an extension so it can be used anywhere (not just in the function).

extension Double {
func reduceScale(to places: Int) -> Double {
let multiplier = pow(10, Double(places))
let newDecimal = multiplier * self // move the decimal right
let truncated = Double(Int(newDecimal)) // drop the fraction
let originalDecimal = truncated / multiplier // move the decimal back
return originalDecimal
}
}

func formatNumber(_ n: Int) -> String {
let num = abs(Double(n))
let sign = (n < 0) ? "-" : ""

switch num {
case 1_000_000_000...:
var formatted = num / 1_000_000_000
formatted = formatted.reduceScale(to: 1)
return "\(sign)\(formatted)B"

case 1_000_000...:
var formatted = num / 1_000_000
formatted = formatted.reduceScale(to: 1)
return "\(sign)\(formatted)M"

case 1_000...:
var formatted = num / 1_000
formatted = formatted.reduceScale(to: 1)
return "\(sign)\(formatted)K"

case 0...:
return "\(n)"

default:
return "\(sign)\(n)"
}
}

You can fine tune this method for specific cases, such as returning 100k instead of 100.5k or 1M instead of 1.1M. This method handles negatives as well.

print(formatNumber(1515)) // 1.5K
print(formatNumber(999999)) // 999.9K
print(formatNumber(1000999)) // 1.0M


Related Topics



Leave a reply



Submit