How to check that the string is not nil in swift? - string

If I declared a String like this: var date = String()
and I want to check if it is a nil String or not,
so that I try something like:
if date != nil{
println("It's not nil")
}
But I got an error like : Can not invoke '!=' with an argument list of type '(#lvalue String, NilLiteralConvertible)'
after that I try this:
if let date1 = date {
println("It's not nil")
}
But still getting an error like:
Bound value in a conditional binding must be of Optional type
So my question is how can I check that the String is not nil if I declare it this way?

The string can't be nil. That's the point of this sort of typing in Swift.
If you want it to be possibly nil, declare it as an optional:
var date : String?
If you want to check a string is empty (don't do this, it's the sort of thing optionals were made to work around) then:
if date.isEmpty
But you really should be using optionals.

You may try this...
var date : String!
...
if let dateExists = date {
// Use the existing value from dateExists inside here.
}
Happy Coding!!!

In your example the string cannot be nil. To declare a string which can accept nil you have to declare optional string:
var date: String? = String()
After that declaration your tests will be fine and you could assign nil to that variable.

Its a bit late but might help others. You can create an optional string extension. I did the following to set an optional string to empty if it was nil :
extension Optional where Wrapped == String {
mutating func setToEmptyIfNil() {
guard self != nil else {
self = ""
return
}
}
}

Related

Flutter converting String to Boolean

I am having a String that i would like to convert to Boolean Below is how the string looks like
String isValid = "false";
The String isValid can either be true or false
Is there a way i can directly convert this String isValid to Boolean. I have tried Sample questions and solutions but they are just converting Strings which are hard coded, for example most of the answers are just when the string is true
On top of my head, you can create an extension method for string data-type for your own need with all sorts of requirements checks and custom exceptions to beautify your desired functionalities. Here is an example:
import 'package:test/expect.dart';
void main(List<String> args) {
String isValid = "true";
print(isValid.toBoolean());
}
extension on String {
bool toBoolean() {
print(this);
return (this.toLowerCase() == "true" || this.toLowerCase() == "1")
? true
: (this.toLowerCase() == "false" || this.toLowerCase() == "0"
? false
: throwsUnsupportedError);
}
}
Here, in this example, I've created a variable named isValid in the main() method, which contains a string value. But, look closely at how I've parsed the string value to a bool value using the power with extension declared just a few lines below.
Same way, you can access the newly created string-extension method toBoolean() from anywhere. Keep in mind, if you're not in the same file where the toBoolean() extension is created, don't forget to import the proper reference.
Bonus tips:
You can also access toBoolean() like this,
bool alternateValidation = "true".toBoolean();
Happy coding 😊
This example can work for you, either if is false or true:
String isValid = "true";
bool newBoolValue = isValid.toLowerCase() != "false";
print(newBoolValue);
You can use extensions like this
bool toBoolean() {
String str = this!;
return str != '0' && str != 'false' && str != '';
}
First of All
You should make the string to lowercase to prevent check the string twice
then you can check if the string equal "true" or not and save the result to bool variable as below:
String isValidString = "false"; // the boolean inside string
bool isValid = isValidString.toLowerCase() == 'true'; // check if true after lowercase
print("isValid=$isValid"); // print the result
I opened a PR for this question, I believe that in the future it will be possible to do something native.
void main() {
print(bool.parse("true")); // true
print(bool.parse("false")); //false
print(bool.parse("TRUE")); // FormatException
print(bool.parse("FALSE")); //FormatException
print(bool.parse("True", caseSensitive: false)); // true
print(bool.parse("False", caseSensitive: false)); // false
if(bool.parse("true")){
//code..
}
}
Reference
https://github.com/dart-lang/sdk/pull/51026

Swift Form Validation - Check if Int or String has been entered

I am trying to validate a form to make sure the user has entered an integer number and not a string. I can check if the number is an integer as follows:
var possibleNumber = timeRetrieved.text
convertedNumber = possibleNumber.toInt()
// convertedNumber is inferred to be of type "Int?", or "optional Int"
if convertedNumber != nil {
println("It's a number!")
totalTime = convertedNumber!
}
My problem is I want to make sure the user has not entered any text, doubles etc. I only want integer numbers. The following code does not work because it evaluates true if the variable is an integer. What code should I use to evaluate if variable is not an integer?
if convertedNumber != nil {
let alertController = UIAlertController(title: "Validation Error", message: "You must enter an integer number!", preferredStyle: .Alert)
let alertAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.Destructive, handler: {(alert : UIAlertAction!) in
alertController.dismissViewControllerAnimated(true, completion: nil)
})
alertController.addAction(alertAction)
presentViewController(alertController, animated: true, completion: nil)
Swift 2 changes this: as both Int("abc") and Int("0") return 0, integer conversion can't be used. You could use this:
class Validation {
static func isStringNumerical(string : String) -> Bool {
// Only allow numbers. Look for anything not a number.
let range = string.rangeOfCharacterFromSet(NSCharacterSet.decimalDigitCharacterSet().invertedSet)
return (range == nil)
}
}
It uses a decimalDigitCharacterSet, and can be changed to use whatever character set you want.
func testIsStringNumerical() {
XCTAssertEqual(SignUpLoyaltyViewController.isStringNumerical("123"), true)
XCTAssertEqual(SignUpLoyaltyViewController.isStringNumerical(""), true)
XCTAssertEqual(SignUpLoyaltyViewController.isStringNumerical("12AA"), false)
XCTAssertEqual(SignUpLoyaltyViewController.isStringNumerical("123.4"), false)
}
This is dramatically faster than the Regex answer. (2000 runs, 0.004s vs regex 0.233s)
If the number the user has entered is not an integer, convertedNumber will be nil. Just add an else clause in which you can show the alert.
Int initializer
This works in Swift 2.2 and above. It is based on Minhal Khan's answer which illustrates that Int has an initializer with this signature: init?(_ text: String, radix: Int = default). Since radix has a default value, it can be left out. *more info on this initializer is found here.
var totalTime: Int?
let possibleInt = timeRetrieved.text ?? ""
if let convertedNumber = Int(possibleInt) {
print("'\(possibleInt)' is an Int")
totalTime = convertedNumber
}
else {
print("'\(possibleInt)' is not an Int")
}
print("totalTime: '\(totalTime)'")
Note: I assumed timeRetrieved is a UITextField. The UITextField text property is an optional string (though programmatically not allowed to be nil). Therefore, the compiler requires it be unwrapped. I used the nil coalescing operator (??) to substitute a nil for empty string which does not yield an integer as desired. Here's a post that discusses the optionality of UITextfield.text.
What i had done was get the value and check if it could convert it, works for me
var enteredText = Int(textfield.text)
if enteredText == nil{
//String entered
}
else{
//Int entered
}
Based on #Graham Perks answer a Swift 3 Version as string extension:
extension String
{
var isNumeric: Bool
{
let range = self.rangeOfCharacter(from: CharacterSet.decimalDigits.inverted)
return (range == nil)
}
}
Usage:
"123".isNumeric // true
"abc".isNumeric // false
I really recommend using a REGEX, I was recently trying to validate 10 digit phone numbers using if let _ = Int(stringToTest)... and on 32 bit hardware, I faced range issues.
func validate(value: String) -> Bool {
let PHONE_REGEX = "\\d{10}"
let phoneTest = NSPredicate(format: "SELF MATCHES %#", PHONE_REGEX)
let result = phoneTest.evaluateWithObject(value)
if result == true {
log.info("'\(self.text!)' is a valid number.")
} else {
log.info("'\(self.text!)' is an invalid number.")
}
return result
}

How to convert a 'string pointer' to a string in Golang?

Is it possible to get the string value from a pointer to a string?
I am using the goopt package to handle flag parsing and the package returns *string only. I want to use these values to call a function in a map.
Example
var strPointer = new(string)
*strPointer = "string"
functions := map[string]func() {
"string": func(){
fmt.Println("works")
},
}
//Do something to get the string value
functions[strPointerValue]()
returns
./prog.go:17:14: cannot use strPointer (type *string)
as type string in map index
Dereference the pointer:
strPointerValue := *strPointer
A simple function that first checks if the string pointer is nil would prevent runtime errors:
func DerefString(s *string) string {
if s != nil {
return *s
}
return ""
}
Generic https://stackoverflow.com/a/62790458/1079543 :
func SafeDeref[T any](p *T) T {
if p == nil {
var v T
return v
}
return *p
}

Swift: String contains String (Without using NSString)?

I have the same problem like in this question:
How do I check if a string contains another string in Swift?
But now a few months later I wonder if it can be done without using NSString?
I nice and simple contains-method would be fine.
I searched the web and the documentation but I found nothing!
Same way, just with Swift syntax:
let string = "This is a test. This is only a test"
if string.rangeOfString("only") != nil {
println("yes")
}
For Swift 3.0
if str.range(of: "abc") != nil{
print("Got the string")
}
String actually provides a "contains" function through StringProtocol.
No extension whatsoever needed:
let str = "asdf"
print(str.contains("sd") ? "yep" : "nope")
https://developer.apple.com/reference/swift/string
https://developer.apple.com/documentation/swift/stringprotocol
If you want to check if your string matches a specific pattern, I can recommend the NSHipster article about NSRegularExpressions: http://nshipster.com/nsregularexpression/
I wrote an extension on String for SWIFT 3.0 so that i could simply call absoluteString.contains(string: "/kredit/")
extension String {
public func contains(string: String)-> Bool {
return self.rangeOfString(string) != nil
}
}
just to demonstrate the use of options.
var string = "This is a test. This is only a test. Not an Exam"
if string.range(of:"ex") != nil {
print("yes")
}
if string.range(of:"ex", options: String.CompareOptions.caseInsensitive) != nil {
print("yes")
}

Get Int from String in Swift

I want to make an Int from an String, but can't find how to.
This is my func:
func setAttributesFromDictionary(aDictionary: Dictionary<String, String>) {
self.appId = aDictionary["id"].toInt()
self.title = aDictionary["title"] as String
self.developer = aDictionary["developer"] as String
self.imageUrl = aDictionary["imageUrl"] as String
self.url = aDictionary["url"] as String
self.content = aDictionary["content"] as String
}
When using toInt() I get the error messag Could not find member 'toInt'. I can't use Int(aDictionary["id"]) either.
Subscripting a dictionary, with the dict[key] method, always returns an optional. For example, if your dictionary is Dictionary<String,String> then subscript will return an object with type String?. Thus the error that you are seeing of "Could not find member 'toInt()'" occurs because String?, an optional, does not support toInt(). But, String does.
You may also note that toInt() returns Int?, an optional.
The recommended approach to your need is something along the lines of:
func setAttributesFromDictionary(aDictionary: Dictionary<String, String>) {
if let value = aDictionary["id"]?.toInt() {
self.appId = value
}
// ...
}
The assignment will occur iff aDictionary has an id mapping and its value is convertible to an Int.
In action:

Resources