WWDC24 SALE: Save 50% on all my Swift books and bundles! >>

SOLVED: Day 7- Returning value with functions and their reasoning

Forums > 100 Days of SwiftUI

Hello,

So in the how to return values from functions in Day 7 I tried the exercise problem: "do two strings contain the same letters, regardless of their order?" this was optional and I tried it and figured it out. However my question regarding this is not how but why.

My first attempt I tried the following:

func twoStrings(firstString: String, secondString: String) -> Bool {

    firstString.sorted()
    secondString.sorted()

    if firstString == secondString {
        return true
    }
    return false
}

twoStrings(firstString: "abc", secondString: "cab")

Why didn't this work? I noticed I had to add "return false" at the end, why did it need that?

After I fixed my solution and got the program to return true with this:

func twoStrings(firstString: String, secondString: String) -> Bool {

    if firstString.sorted() == secondString.sorted() {
        return true
    }
    return false
}

twoStrings(firstString: "abc", secondString: "cab")

Was this way of doing it unnecessary maybe not the best practice? I know it worked but I don't want to pick up bad habits and I want to know why. It bothered me that it looked a little too different to Pauls solution below.

func areLettersIdentical(string1: String, string2: String) -> Bool {
    let first = string1.sorted()
    let second = string2.sorted()
    return first == second
}

So in conclusion, Which one was the better solution? To me it seems that writing a bit more code for readability is a good idea for example when I used if statements and return to make it clear what I was doing, but paul keeps showing us ways of deleting "unnecessary code" how do you know when you should sacrifice readability for shorter maybe more abstract code? Hopefully this makes sense thank you for your time reading and I look forward to your answers.

   

Why didn't this work?

Because these lines:

firstString.sorted()
secondString.sorted()

sort firstString and secondString and return the sorted values, but you don't assign those sorted values to anything.

And then in this line:

if firstString == secondString {

you compare the original unsorted firstString and original unsorted secondString rather than the sorted values you thought you were comparing.

But in your corrected code:

if firstString.sorted() == secondString.sorted() {

you are comparing the sorted values with one another and it works.

I noticed I had to add "return false" at the end, why did it need that?

Because all functions must return a value and you have to explicitly tell the function what value to return.*

* Unless the return value is Void, in which case you are likely also leaving off the explicit return type in the function declaration.

Which one was the better solution?

They're both perfectly fine.

If it were me, I would go with Paul's way, for one reason: There is only a single place in the code where you return from the function, versus two exit points in your code. But that's really a stylistic preference more than anything else.

1      

Thank you for your reply and I understand your points. However before I mark this as solved you still haven't answered my last question, When do you know whether to write more code for the sake of readability or shorter code that's maybe more difficult to understand at first glance for the sake of efficiency or performance? For example for some people the ternary operator is more difficult to understand what's going on rather than just writing if statements. Is it longer? yes but It's obvious what I'm trying to do.

   

When do you know whether to write more code for the sake of readability or
shorter code that's maybe more difficult to understand at first glance?

Here's an example from another post.

I defined a bool, named showingSheet, that decides if a slide up sheet should be displayed. I want to set this variable to true, if the array of items is empty. This is a long version of that logic:

@State private var showingSheet = false
... snip ...

if ( myList.items.count == 0 ) {
    showingSheet = true 
    } else {
    showingSheet = false
}

Perfectly fine code, but verbose. What may trouble some, is the way the programmer needs to know the internal structure of my class. Here the programmer needs to know that I have a property named items, and that property is an array. Then they have to select an array function to determine if the array has content.

This is a long chunk of code.

Alternative

Instead, I added a computed variable in my class named itemsIsEmpty. This var returns a boolean if the internal array is empty or not. The benefit here is I can protect the inner elements of my class from others who may want to use it in their code. Additionally, I provide a convenience variable for the programmer. They don't need to know my class' structure, but they get the same features.

The other benefit, in my opinion, is this approach greatly simplifies updating the showingSheet variable. showingSheet only needs to be true if the internal array is empty. Luckily there's a variable that provides that exact information!

Here's a more terse version of that logic:

@State private var showingSheet = false
... snip ...

showingSheet = myList.itemsIsEmpty

Which is easier to understand?

I think the first example looks like a plate full of C++ spaghetti 🍝 logic. I think it's easier to 'read' the second as it follows a single line of logic.

1      

Addressing another point...

{...factor code...} for the sake of efficiency or performance?

Your iPhone or iPad can execute millions of logic decisions each second. MILLIONS! When you drag your finger across its screen your iPhone is performing tens of thousands of calculations determining distances, velocity, pressures, directions, pauses, and more. iOS is highly tuned and the Apple silicon processors are insane.

I think trying to re-write a ternary operation into a longer if-statement for the sake of efficiency or performance is completely unnecessary. Your iPhone won't even feel it.

Keep Coding!

1      

Thank you both for answering my questions, I feel better now that I got some clarity!

   

Save 50% in my WWDC sale.

SAVE 50% To celebrate WWDC24, all our books and bundles are half price, so you can take your Swift knowledge further without spending big! Get the Swift Power Pack to build your iOS career faster, get the Swift Platform Pack to builds apps for macOS, watchOS, and beyond, or get the Swift Plus Pack to learn advanced design patterns, testing skills, and more.

Save 50% on all our books and bundles!

Reply to this topic…

You need to create an account or log in to reply.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.