How to use if let with another statement in swift? - string

If want to both assign a string and check that its not empty in Swift.
if let alternative3Text = attributes.stringForKey("choiceThree") && alternative3Text != "" {
// do stuff with alternative3Text
}
Is this possible in Swift, or do i have to do a nested if-statement?

Update: As of Swift 3 (Xcode 8), additional clauses are
separated by a comma, not by where:
if let alternative3Text = attributes.string(forKey: "choiceThree"),
alternative3Text != "" {
// do stuff with alternative3Text
}
Update: As of Swift 1.2 (Xcode 6.3 beta), you can combine
optional binding with additional conditions:
if let alternative3Text = attributes.stringForKey("choiceThree") where alternative3Text != "" {
// do stuff with alternative3Text
}
Using switch-case still works but is not necessary anymore for this purpose.
Old answer:
It is not possible with an if statement, but with switch.
A switch case can use a where clause to check for additional conditions
(documentation).
Assuming (from your question) that attributes.stringForKey("choiceThree") returns
String?, the following would work:
switch (attributes.stringForKey("choiceThree")) {
case .Some(let alternative3Text) where alternative3Text != "":
// alternative3Text is the unwrapped String here
default:
break
}

No, you can't require additional expressions to be true in an if let statement. You will need to add additional code to do this in either the form of a nested if statement as you've already mentioned, or in some other way. If your only requirement is to keep this statement looking clean and wouldn't mind moving some of the logic elsewhere, you could always make an extension to what ever type your attributes variable is to add this functionality.
Here's an example if attributes was an instance of NSUserDefaults. (just because it already contains a stringForKey() instance method.)
extension NSUserDefaults {
func nonEmptyStringForKey(key: String) -> String? {
let full = self.stringForKey(key)
return full != "" ? full : nil
}
}
And then use it like this
if let alternative3Text = attributes.nonEmptyStringForKey("choiceThree") {
// stuff
}

Related

Is there a shorter replacement for Kotlin's deprecated String.capitalize() function?

Kotlin deprecated the capitalize function on String class, and their suggested replacement is obnoxiously long. This is an example of a situation where they made the right call on deprecating it, but the wrong call on the user experience.
For example, this code:
val x = listOf("foo", "bar", "baz").map { it.capitalize() }
is "cleaned up" by the IDE to become:
val x = listOf("foo", "bar", "baz").map { it.replaceFirstChar {
if (it.isLowerCase()) it.titlecase(
Locale.getDefault()
) else it.toString()
} }
This is preeeeetty ugly. What can we do about it?
The suggested replacement is ugly because it needs to be equivalent to what capitalize() used to do:
dependent on the default locale
NOT converting an uppercase first char into titlecase (e.g.
capitalize does NOT transform a leading 'DŽ' into 'Dž' - both are single characters here, try to select them)
If you didn't care too much about this behaviour, you can use a simpler expression using an invariant locale and unconditionally titlecasing the first character even if uppercase:
val x = listOf("foo", "bar", "baz").map { it.replaceFirstChar(Char::titlecase) }
This means that if the first character is uppercase like 'DŽ', it will be transformed into the titlecase variant 'Dž' anyway, while the original code wouldn't touch it. This might actually be desirable.
One of the reasons capitalize() has been deprecated is because the behaviour of the method was unclear. For instance:
behaviour #2 is pretty weird
not capitalizing words in a sentence might be unexpected (C# would titlecase every space-separated word)
not lowercasing other characters of the words might be unexpected as well
If you want to keep the exact current behaviour on purpose, but make it more convenient to use, you can always roll your own extension function with a name that suits you ("capitalize(d)" might not give enough info to the unaware reader):
fun String.titlecaseFirstCharIfItIsLowercase() = replaceFirstChar {
if (it.isLowerCase()) it.titlecase(Locale.getDefault()) else it.toString()
}
Or for the version with invariant locale that titlecases the uppercase chars:
fun String.titlecaseFirstChar() = replaceFirstChar(Char::titlecase)
A neat solution is to define a new extension function on String, which hides the gory details with a cleaner name:
/**
* Replacement for Kotlin's deprecated `capitalize()` function.
*/
fun String.capitalized(): String {
return this.replaceFirstChar {
if (it.isLowerCase())
it.titlecase(Locale.getDefault())
else it.toString()
}
}
Now your old code can look like this:
val x = listOf("foo", "bar", "baz").map { it.capitalized() }
You'll need to define the extension function at the top level in some package that you can import easily. For example, if you have a kotlin file called my.package.KotlinUtils (KotlinUtils.kt), and you put the definition inside it like so:
package my.package
fun String.capitalized(): String {...}
Then you can import it in your other packages with:
import my.package.capitalized
val fruits = listOf("baNana", "avocAdo", "apPle", "kiwifRuit")
fruits
.filter { it.startsWith("a") }
.sortedBy { it }
.map { it.lowercase().replaceFirstChar(Char::uppercase) }
.forEach { println(it) }
Output:
Apple
Avocado
You can call the replaceFirstChar function on the original string and pass the transform function as input. The transform function takes the first character and converts it to an uppercase character using the uppercase() function.
val list = listOf("foo", "bar", "baz") .map {
it.replaceFirstChar { firstChar ->
firstChar.uppercase()
}
}
println("List - > $list")
Output
List - > [Foo, Bar, Baz]
How about this?
fun main() {
val x = listOf("foo", "bar", "baz").map { it[0].uppercase() + it.drop(1) }
println(x)
}
Output:
[Foo, Bar, Baz]
If you are not sure (maybe you receive Strings from an API) if the first letter is upper or lower case , you can use the below method;
var title = "myTitle"
title.replaceFirstChar {
if (it.isLowerCase()) it.titlecase(Locale.getDefault()) else
it.toString()
}
New title will be "MyTitle"
You can use this extension function to capitalize first characture of String
fun String.capitalize(): String {
return this.replaceFirstChar {
if (it.isLowerCase()) it.titlecase(Locale.getDefault())
else it.toString()
}
}
And call this method like
"abcd".capitalize()
I found a method trying to capitalize a string that came from the API and it apparently worked, found it in the Kotlin docs:
println("kotlin".replaceFirstChar { it.uppercase() }) // Kotlin
and use it like this in my code:
binding.textDescriptions.text = "${it.Year} - ${it.Type.replaceFirstChar {it.uppercase()}}"

Check equaling enum without parameter

I use enums but can't find good way to check eqauling.
enum Turn {
A(value:Int);
B(value:Int);
}
class Test {
static function main() {
var turn = Turn.A(100);
//I want to Check turn is Turn.A(any value) without using 'switch'.
if (turn == Turn.A) ...
}
}
Is there any good and simple way to checking?
You can use the .match() function:
if (turn.match(Turn.A(_)))
I haven't tested this, but it might be faster using Type class:
if (Type.enumConstructor(turn) == "A") ...
Because it is unsafe ("A" could be a typo), I suggest to use ExprTools:
import haxe.macro.ExprTools.*;
if (Type.enumConstructor(turn) == toString(macro A)) ...
There is another way, but I don't think it is faster :
if (Type.enumIndex(turn) == Type.enumIndex(A(0))) ...
And you might get condition evaluated to true for different enums:
enum Color { Red; }
if (Type.enumIndex(turn) == Type.enumIndex(Red)) ... // true

Elegant way to check if multiple strings are empty

How can I check if multiple strings are empty in an elegant way? This is how I currently do it:
//if one required field is empty, close the connection
if (registerRequest.Email == "") ||
(registerRequest.PhoneNumber == "")||
(registerRequest.NachName =="") ||
(registerRequest.VorName =="") ||
(registerRequest.Password =="") ||
(registerRequest.VerificationId ==""){
//Could not proceed
w.WriteHeader(UNABLE_TO_PROCEED)
w.Write([]byte("Unable to register account."))
return
}
Note: You may use the solution below if you keep the "is-valid" condition in your handler, and also if you separate your condition into another function or method.
You can create a simple helper function, which has a variadic parameter, and you can call it with any number of string values:
func containsEmpty(ss ...string) bool {
for _, s := range ss {
if s == "" {
return true
}
}
return false
}
Example using it:
if containsEmpty("one", "two", "") {
fmt.Println("One is empty!")
} else {
fmt.Println("All is non-empty.")
}
if containsEmpty("one", "two", "three") {
fmt.Println("One is empty!")
} else {
fmt.Println("All is non-empty.")
}
Output of the above (try it on the Go Playground):
One is empty!
All is non-empty.
Your example would look like this:
if containsEmpty(registerRequest.Email,
registerRequest.PhoneNumber,
registerRequest.NachName,
registerRequest.VorName,
registerRequest.Password,
registerRequest.VerificationId) {
// One of the listed strings is empty
}
Also registerRequest is a kinda long name, it could be shortened to like r. If you can't or don't want to rename it in the surrounding code and if you want to shorten the condition, you could also do something like this:
If registerRequest is a pointer (or interface), you could also write:
if r := registerRequest; containsEmpty(r.Email,
r.PhoneNumber,
r.NachName,
r.VorName,
r.Password,
r.VerificationId) {
// One of the listed strings is empty
}
Actually you can do this even if registerRequest is not a pointer, but then the struct will be copied. If registerRequest is a struct, then you can take its address to avoid having to copy it like this:
if r := &registerRequest; containsEmpty(r.Email,
r.PhoneNumber,
r.NachName,
r.VorName,
r.Password,
r.VerificationId) {
// One of the listed strings is empty
}
As Mario Santini mentioned in comment, a way to increase testability, encapsulate this logic, and decouple it from your handler method (which judging by the number of fields looks like it is at risk of changing at a different rate than your handler) could be to put this logic in a function:
func validRequest(registerRequest ?) bool {
return registerRequest.Email == "" ||
registerRequest.PhoneNumber == "" ||
registerRequest.NachName == "" ||
registerRequest.VorName == "" ||
registerRequest.Password == "" ||
registerRequest.VerificationId == ""
}
This now supports very focused, table driven tests, that can exercise what it means to be a valid request independent of any method involving writing headers.
It allows you to verify the valid/invalid path of your enclosing function, but to have very focused tests here. It also allows you to change what it means to be a valid request and verify it independent of your enclosing function.
You can use a switch:
switch "" {
case registerRequest.Email,
registerRequest.NachName,
registerRequest.Password,
registerRequest.PhoneNumber,
registerRequest.VerificationId,
registerRequest.VorName:
w.WriteHeader(UNABLE_TO_PROCEED)
w.Write([]byte("Unable to register account."))
return
}
https://golang.org/ref/spec#Switch_statements

PHP-like string parsing

I'm writing a mini-console of sorts and I'm trying to figure out how to extract things from a link. For example, in PHP this is a request variable
so:
http://somelink.com/somephp.php?variable1=10&variable2=20
Then PHP figures out the url parameters and assigns them to a variable.
How would I parse something like this in Swift?
So, given the string I'd want to take: variable1=10 and variable2=20 etc, is there a simple way to do this? I tried googling around but didn't really know what I was searching for.
I have a really horrible hacky way of doing this but it's not really extendable.
You’d be wanting NSURLComponents:
import Foundation
let urlStr = "http://somelink.com/somephp.php?variable1=10&variable2=20"
let components = NSURLComponents(string: urlStr)
components?.queryItems?.first?.name // Optional("variable1")
components?.queryItems?.first?.value // Optional("10")
You might find it helpful to add a subscript operator for the query items:
extension NSURLComponents {
subscript(queryItemName: String) -> String? {
// of course, if you do this a lot,
// cache it in a dictionary instead
for item in self.queryItems ?? [] {
if item.name == queryItemName {
return item.value
}
}
return nil
}
}
if let components = NSURLComponents(string: urlStr) {
components["variable1"] ?? "No value"
}

Compare enum without considering its arguments

Let me make this clear, I have this enum:
enum Token {
Number(v:Float);
Identifier(v:String);
TString(v:String);
Var;
Assign;
Division;
// and so on
}
I want to check if the value of a variable is an Identifier, but this doesn't work:
if(tk == Token.Identifier) {
It only allows me to compare the values if I pass arguments:
if(tk == Token.Identifier('test')) {
But this will only match if the identifier is 'test', but I want to match any identifier.
Type.enumConstructor(tk) == "Identifier"
Read the Type doc for more methods on enum.
Update (2019-02-04):
At the time of writing this answer it was still Haxe 2.06. Much have changed since then.
At this moment, for Haxe 3 (or 4), I would recommend pattern matching, specifically using single pattern check instead:
if (tk.match(Identifier(_)) ...
which is a short hand for
if (switch tk { case Identifier(_): true; case _: false; }) ...
_ is the wildcard that matches anything.
alternatively:
static function isIdentifier(token : Token) return switch(token) { case Token.Identifier(_): true; default: false; }
Using "using" you should also be able to do:
if(tk.isIdentifier()) {
Or even:
tk.match(Token.Identifier(_));

Resources