UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

SOLVED: Question about new way to good code

Forums > SwiftUI

Hello everyone!

I'm working on a app and trying to write code on the best way.

I have a View with 3 textfields and I want to join the three strings when an user press one button.

I create this func but I think there a more efficient way to do this.

Thanks!

func groupStrings(str1 : String, str2: String, str3: String) -> String {
        var arrStr : [String] = []
        if str1 != ""{
            arrStr.append(str1)
        }
        if str2 != "" {
            arrStr.append(str2)
        }
        if str3 != "" {
            arrStr.append(str3)
        }
        return arrStr.joined(separator: ", ")
    }

2      

hi,

  • i would first change the argument to be a sinlge array of strings, so you won't have to write another function in a different view when you pass in, say, 2 string or 5 strings. so the signature would be
    func groupStrings(str: [String]) -> String
  • use the filter function to extract only the non-empty strings from the array str, and then call joined on the result, like this
    return str.filter({ !0.isEmpty }).joined(separator: ", ")

that's it!

func groupStrings(str: [String]) -> String {
    str.filter({ !0.isEmpty }).joined(separator: ", ") // there is no need to explicitly write the return statement
}

obviously, you'd change the way you call the function ... instead of

let myJoinedStrings = groupStrings(str1: textInField1, str2: textInField2, str3: textInField3)

you would write

let myJoinedStrings = groupStrings(str: [textInField1, textInField2, textInField3])

hope that helps,

DMG

3      

I have slightly different way. With this you do not have to put the String into an array in call.

func groupStrings(_ string : String...) -> String {
    string.filter { !$0.isEmpty }.joined(separator: " ")
}

let joinString = groupStrings(textInField1, textInField2, textInField3, textInField4)

print(joinString)

However if really want to make reusable then

func groupStrings(_ string : String..., separator: String = " ") -> String {
    string.filter { !$0.isEmpty }.joined(separator: separator)
}
let fullName = groupStrings(firstName, lastName)
let fullAddress = groupStrings(street, city, zip, separator: "\n")

print(fullName)
print(fullAddress)

2      

David: This shows you the truth about Swift. There are many ways to accomplish a simple task!

I think @delaware's approach with filter is clever, but as he pointed out, it requires you to first put your strings into an array. This doesn't seem too objectionable, until @nigel proposed his response!

@Nigel gets my vote for the [Solved] tag. I only wish @nigel would have taken a paragraph or two to explain the String... notation in the function's parameter list.

2      

3      

BUILD THE ULTIMATE PORTFOLIO APP Most Swift tutorials help you solve one specific problem, but in my Ultimate Portfolio App series I show you how to get all the best practices into a single app: architecture, testing, performance, accessibility, localization, project organization, and so much more, all while building a SwiftUI app that works on iOS, macOS and watchOS.

Get it on Hacking with Swift+

Sponsor Hacking with Swift and reach the world's largest Swift community!

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

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.