Why is this string comparison not working? - swift-playground

I have defined a function in swift that will take two strings as parameters and return true if they are the same:
func compareString(f_string:String,S_string:String)->Bool{
if f_string == S_string{
return true
}
}
Why does it show an error message?

your function is supposed to return a boolean value everytime, but it returns only when the strings are equal. add a return false statement after if and it should work.
func compareString(f_string:String,S_string:String)->Bool{
if f_string == S_string{
return true
}
return false
}

Related

How to show a text when ForEach with a filter option shows no result in Swiftui?

I am trying to solve the following problem. I created a "List looking like " List with ForEach Loops. Which works just fine just not for one problem. In the last ForEach loop I would like to give a result in text if there is no result in the database "values". So if the ForEach loop does not go thru because there is no database set then I would like to give a Text result saying "0€".
Do you have any ideas?
Here the code:
ForEach(categories.filter({ (categories) -> Bool in
categories.inOrOutCategory_ID == 1 }), id: \.category_ID) { categoryIndex in
Section(header: Text("\(categoryIndex.category)")) {
ForEach(subCategories.filter({ (subCategories) -> Bool in
subCategories.category_ID == categoryIndex.category_ID }), id: \.subCategory_ID) {
subCategoryIndex in
HStack {
Text("\(subCategoryIndex.subCategory)").padding(.leading)
Spacer()
ForEach(values.filter({ (values) -> Bool in
values.subCategory_ID == subCategoryIndex.subCategory_ID && (values.month_ID == self.month && (values.year == self.year)) }), id: \.value_ID) { valueIndex in
Text("\(String(format: "%.2f", valueIndex.value))€").padding(.trailing)
}
}
}
}
}.padding(.leading)
Thank you very much
I had the same problem today, the solution would be to create a method which would be true or false which checks the conditions of the filters manually then it will be necessary to create the view in swiftUI which is displayed if the method returns false (no result ) for example and in your view you display a text or whatever you want with no results
example :
func searchResult() -> Bool {
if searchText == "" {
return true // ne s'affiche pas
}
for u in subscribers{
if u.firstname.contains(searchText){
return true
}
if u.lastname.contains(searchText){
return true
}
}
return false // s'affiche
}
in you view :
if !searchResult() {
Text("test")
}

Why is my struct method always returning false?

I'm trying to do validation on my form struct in a method that returns a bool, but I keep getting false even when it should be returning true..
If you look towards the end of the Validate method, you'll see I write validated := len(this.Errors) == 0 which should be making "validated" either true or false based on whether the Errors map has items or not, and then I return validated.
When I fill out my form accurately, there should be no errors yet I still get false when I should be getting true.
Can someone explain? Is this not how Go works?
form.go:
package models
import (
"../config"
"../util"
)
type Form struct {
Name string
Email string
Phone string
Message string
Thanks string
ErrorHandler
}
func (this *Form) Validate() bool {
this.Errors = make(map[string]string)
matched := util.MatchRegexp(".+#.+\\..+", this.Email)
if !util.IsEmpty(this.Email) {
if matched == false {
this.Errors["Email"] = config.EMAIL_INVALID
}
} else {
this.Errors["Email"] = config.EMAIL_EMPTY
}
if util.IsEmpty(this.Name) {
this.Errors["Name"] = config.NAME_EMPTY
}
if util.IsEmpty(this.Phone) {
this.Errors["Phone"] = config.PHONE_EMPTY
}
if util.IsEmpty(this.Message) {
this.Errors["Message"] = config.MESSAGE_EMPTY
}
validated := len(this.Errors) == 0
if validated {
this.Thanks = config.THANK_YOU
}
return validated
}
errorhandler.go:
package models
type ErrorHandler struct {
Errors map[string]string
}
func (this *ErrorHandler) HandleErr(err string) {
this.Errors = make(map[string]string)
this.Errors["Error"] = err
}
And this is where I try to call the Validate method -- in a function in my controller:
form := &models.Form{
Name: r.FormValue("name"),
Email: r.FormValue("email"),
Phone: r.FormValue("phone"),
Message: r.FormValue("message")}
if form.Validate() {
// This never runs because 'form.Validate()' is always false
}
I don't think the util.IsEmpty() is the culprit here.. just checks if the string is empty:
func IsEmpty(str string) bool {
return strings.TrimSpace(str) == ""
}
Any help would be appreciated!
It's best to debug this kind of problem with a log statement like:
log.Printf("form: %v", form)
before calling validate, so it's clear what the input data looks like.
Greetings, Philip

How do I write a generic recursive function that takes a CollectionType in Swift?

How would you create a generic function to process a CollectionType in Swift? For example, I want something that boils down to this:
func f<C: CollectionType>(list: C) {
if list.isEmpty {
return
}
else {
f(list.dropFirst()) // causes error
}
}
This causes an error because SubSequence might not be a CollectionType: Cannot invoke 'f' with an argument list of type '(C.SubSequence)'
I tried working around it by constraining the SubSequence type like this:
<C: CollectionType where C.SubSequence: CollectionType>
I get the same error, though. Any suggestions on how to write a generic recursive function for CollectionType?
To fix your error, you can transform a SubSequence into an array with the Array initializer:
func f<C: CollectionType>(list: C) {
if list.isEmpty {
return
}
else {
f(Array(list.dropFirst()))
}
}
Here's a solution that doesn't require copying the storage in a new array with every iteration:
func f<C: CollectionType
where C.SubSequence: CollectionType,
C.SubSequence == C.SubSequence.SubSequence>(c: C) {
guard let first = c.first else { return }
print(first)
f(c.dropFirst())
}
In Swift 3:
func f<C>(_ c: C) where
C: Collection,
C.SubSequence: Collection,
C.SubSequence == C.SubSequence.SubSequence {
guard !c.isEmpty else { return }
f(c.dropFirst())
}
f([1, 2, 3])

how to compare two optional NSArrays in Swift

Let's have two optional NSArrays. The goal is to check, if they are equal. My solution is
func isArrayEqualToArray(array1:NSArray?, array2:NSArray?) -> Bool {
let areBothEmpty:Bool = array1 == nil && array2 == nil
var areBothEqual:Bool
if !areBothEmpty && array2 != nil {
areBothEqual = array1?.isEqualToArray(array2!) ?? false
} else {
areBothEqual = false
}
let result = areBothEqual || areBothEmpty
return result
}
I feel that it is a little too verbose. It should be doable in a more concise and readable way. Does anyone have a better solution?
It is quite simple:
func isArrayEqualToArray(array1: NSArray?, array2: NSArray?) -> Bool {
return array1 == array2
}
does exactly what you want.
Why does it work? Here == is the operator that compares optionals
func ==<T : Equatable>(lhs: T?, rhs: T?) -> Bool
and that gives true if both operands are nil, or of both
operands are non-nil and the unwrapped operands are equal.
Also NSArray inherits from NSObject which conforms to Equatable,
and comparing NSObjects with == uses the isEqual: method, which is
implemented as isEqualToArray: on NSArray.
Therefore
array1 == array2
gives the same result as
array1.isEqualToArray(array2)
Yes, indeed, you don't need to overcomplicate things:
func isArrayEqualToArray(array1: NSArray?, array2: NSArray?) -> Bool {
if array1 == nil && array2 == nil {
return true;
}
if array1 != nil && array2 != nil {
return array1!.isEqualToArray(array2!);
}
return false;
}
Using a switch statement may be clearer:
func isArrayEqualToArray(a1: NSArray?, a2: NSArray?) -> Bool {
switch (a1,a2) {
case (.Some(a1),.Some(a2)):
return a1.isEqualToArray(a2)
case (.None,.None):
return true
default:
return false
}
}
I liked #The Paramagnetic Croiss answer but I'm still going to shorten it a bit because I see that I can.
```
func isArrayEqualToArray(array1: NSArray?, array2: NSArray?) -> Bool {
if array1 == array2 {
return true;
}
if array1 != nil && array2 != nil {
return array1!.isEqualToArray(array2!);
}
return false;
}
```

Validate NSString for Hexadecimal value

I'm working on a custom NSFormatter.
I need to verify user input step by step... i thought to check by isPartialStringValid: if the string contains only permitted chars "0123456789ABCDEF".
How can i verify this condition ? is there a way with NSString function to check if a string contain only some chars ?
Does this method work for you?
NSString *string = #"FF";
NSCharacterSet *chars = [[NSCharacterSet
characterSetWithCharactersInString:#"0123456789ABCDEF"] invertedSet];
BOOL isValid = (NSNotFound == [string rangeOfCharacterFromSet:chars].location);
Swift 5
extension String {
var isHexNumber: Bool {
filter(\.isHexDigit).count == count
}
}
print("text1".isHexNumber) // false
print("aa32".isHexNumber) // true
print("AD1".isHexNumber) // true
You can create a custom NSCharacterSet that contains the permitted characters (+ characterSetWithCharactersInString:) and then test the string against it with rangeOfCharacterFromSet:. If the returned range is equal to the entire range of the string, you have a match.
Another option would be matching with NSRegularExpression.
Sample code Swift:
func isValidHexNumber() -> Bool {
guard isEmpty == false else { return false }
let chars = CharacterSet(charactersIn: "0123456789ABCDEF").inverted
return uppercased().rangeOfCharacter(from: chars) == nil
}
In swift 2.1 you can extends String in this way:
extension String {
func isValidHexNumber() -> Bool {
let chars = NSCharacterSet(charactersInString: "0123456789ABCDEF").invertedSet
guard self.uppercaseString.rangeOfCharacterFromSet(chars) != nil else {
return false
}
return true
}
}
Swift one-liner without adding any extensions:
myString.allSatisfy(\.isHexDigit)
Using a keypath predicate was introduced in Swift 5.2 prior to that you could use:
myString.allSatisfy({ $0.isHexDigit })

Resources