Swift String hasPrefix Using an Array of Strings












3















I want to avoid the if statement in the sample code below, and instead make a single call to hasPrefix on my number string and pass in the prefixes array. Is there a way to do this in Swift?



let prefixes: [String] = ["212", "213", "214"]
let number: String = "213-555-1212"

if number.hasPrefix("212") || number.hasPrefix("213") {
print("found")
}









share|improve this question




















  • 1





    The answer to your question is in @vacawama's comment prefixes.contains(where: number.hasPrefix)

    – Leo Dabus
    Nov 16 '18 at 10:40






  • 1





    @LeoDabus, I moved it to an answer since the other poster seems unwilling to incorporate constructive feedback.

    – vacawama
    Nov 16 '18 at 12:47
















3















I want to avoid the if statement in the sample code below, and instead make a single call to hasPrefix on my number string and pass in the prefixes array. Is there a way to do this in Swift?



let prefixes: [String] = ["212", "213", "214"]
let number: String = "213-555-1212"

if number.hasPrefix("212") || number.hasPrefix("213") {
print("found")
}









share|improve this question




















  • 1





    The answer to your question is in @vacawama's comment prefixes.contains(where: number.hasPrefix)

    – Leo Dabus
    Nov 16 '18 at 10:40






  • 1





    @LeoDabus, I moved it to an answer since the other poster seems unwilling to incorporate constructive feedback.

    – vacawama
    Nov 16 '18 at 12:47














3












3








3


0






I want to avoid the if statement in the sample code below, and instead make a single call to hasPrefix on my number string and pass in the prefixes array. Is there a way to do this in Swift?



let prefixes: [String] = ["212", "213", "214"]
let number: String = "213-555-1212"

if number.hasPrefix("212") || number.hasPrefix("213") {
print("found")
}









share|improve this question
















I want to avoid the if statement in the sample code below, and instead make a single call to hasPrefix on my number string and pass in the prefixes array. Is there a way to do this in Swift?



let prefixes: [String] = ["212", "213", "214"]
let number: String = "213-555-1212"

if number.hasPrefix("212") || number.hasPrefix("213") {
print("found")
}






swift






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 15 '18 at 21:38









rmaddy

241k27315380




241k27315380










asked Nov 15 '18 at 21:30









AdamAdam

1942514




1942514








  • 1





    The answer to your question is in @vacawama's comment prefixes.contains(where: number.hasPrefix)

    – Leo Dabus
    Nov 16 '18 at 10:40






  • 1





    @LeoDabus, I moved it to an answer since the other poster seems unwilling to incorporate constructive feedback.

    – vacawama
    Nov 16 '18 at 12:47














  • 1





    The answer to your question is in @vacawama's comment prefixes.contains(where: number.hasPrefix)

    – Leo Dabus
    Nov 16 '18 at 10:40






  • 1





    @LeoDabus, I moved it to an answer since the other poster seems unwilling to incorporate constructive feedback.

    – vacawama
    Nov 16 '18 at 12:47








1




1





The answer to your question is in @vacawama's comment prefixes.contains(where: number.hasPrefix)

– Leo Dabus
Nov 16 '18 at 10:40





The answer to your question is in @vacawama's comment prefixes.contains(where: number.hasPrefix)

– Leo Dabus
Nov 16 '18 at 10:40




1




1





@LeoDabus, I moved it to an answer since the other poster seems unwilling to incorporate constructive feedback.

– vacawama
Nov 16 '18 at 12:47





@LeoDabus, I moved it to an answer since the other poster seems unwilling to incorporate constructive feedback.

– vacawama
Nov 16 '18 at 12:47












4 Answers
4






active

oldest

votes


















3














This can be done succinctly with:



if prefixes.contains(where: number.hasPrefix) {
print("found")
}


So, how does this work?




  1. contains(where:) takes a closure that gets called for each element of the prefixes array to decide if the element matches the desired condition. Since prefixes is an array of String, that closure has the signature (String) -> Bool, meaning it takes a String and returns a Bool. contains(where:) will continue to call the given closure for each element in the prefixes array until it gets a true returned, or until it runs out of items in the prefixes array, at which time the answer is false (prefixes doesn't contain an item that matches the condition).


  2. In this case, we are passing the function number.hasPrefix as the closure. Normally you'd use number.hasPrefix by calling it with an argument like this: number.hasPrefix("212"). Without the argument, number.hasPrefix refers to the function hasPrefix called on number and that function has the signature we're looking for: (String) -> Bool. So it can be used as the closure for contains(where:).


  3. So, prefixes.contains(where: number.hasPrefix) takes each prefix from the array and checks if number.hasPrefix(prefix) returns true. If it finds one, it stops searching and returns true. If all of them return false, then prefixes.contains(where:) returns false.







share|improve this answer

































    0














    You can try



    if prefixes.filter { number.hasPrefix($0)}.count != 0 {

    }


    Or



    !prefixes.filter { number.hasPrefix($0)}.isEmpty 


    Or



    prefixes.contains { number.hasPrefix($0) }





    share|improve this answer


























    • Even better !prefixes.filter { number.hasPrefix($0)}.isEmpty

      – EmilioPelaez
      Nov 15 '18 at 21:34






    • 1





      You can't use trailing closure in an if without adding some parentheses. You can do if prefixes.contains(where: number.hasPrefix) { though.

      – vacawama
      Nov 15 '18 at 22:27






    • 1





      But this way you gonna iterate over all array, even first element has prefix you're looking for.

      – user28434
      Nov 16 '18 at 13:15



















    0














    How about:



    prefixes.forEach { prefix in
    if number.hasPrefix(prefix) {
    print("found")
    }
    }


    You might want to make sure that the prefixes array has no duplicates (= is effectively a set).






    share|improve this answer































      0














      If readability is important, you might try this:



      extension String {
      func hasAnyPrefix(_ prefixes: [String]) -> Bool {
      return prefixes.contains { self.hasPrefix($0) }
      }
      }

      if number.hasAnyPrefix(prefixes) {
      print("found")
      }





      share|improve this answer























        Your Answer






        StackExchange.ifUsing("editor", function () {
        StackExchange.using("externalEditor", function () {
        StackExchange.using("snippets", function () {
        StackExchange.snippets.init();
        });
        });
        }, "code-snippets");

        StackExchange.ready(function() {
        var channelOptions = {
        tags: "".split(" "),
        id: "1"
        };
        initTagRenderer("".split(" "), "".split(" "), channelOptions);

        StackExchange.using("externalEditor", function() {
        // Have to fire editor after snippets, if snippets enabled
        if (StackExchange.settings.snippets.snippetsEnabled) {
        StackExchange.using("snippets", function() {
        createEditor();
        });
        }
        else {
        createEditor();
        }
        });

        function createEditor() {
        StackExchange.prepareEditor({
        heartbeatType: 'answer',
        autoActivateHeartbeat: false,
        convertImagesToLinks: true,
        noModals: true,
        showLowRepImageUploadWarning: true,
        reputationToPostImages: 10,
        bindNavPrevention: true,
        postfix: "",
        imageUploader: {
        brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
        contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
        allowUrls: true
        },
        onDemand: true,
        discardSelector: ".discard-answer"
        ,immediatelyShowMarkdownHelp:true
        });


        }
        });














        draft saved

        draft discarded


















        StackExchange.ready(
        function () {
        StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53328176%2fswift-string-hasprefix-using-an-array-of-strings%23new-answer', 'question_page');
        }
        );

        Post as a guest















        Required, but never shown

























        4 Answers
        4






        active

        oldest

        votes








        4 Answers
        4






        active

        oldest

        votes









        active

        oldest

        votes






        active

        oldest

        votes









        3














        This can be done succinctly with:



        if prefixes.contains(where: number.hasPrefix) {
        print("found")
        }


        So, how does this work?




        1. contains(where:) takes a closure that gets called for each element of the prefixes array to decide if the element matches the desired condition. Since prefixes is an array of String, that closure has the signature (String) -> Bool, meaning it takes a String and returns a Bool. contains(where:) will continue to call the given closure for each element in the prefixes array until it gets a true returned, or until it runs out of items in the prefixes array, at which time the answer is false (prefixes doesn't contain an item that matches the condition).


        2. In this case, we are passing the function number.hasPrefix as the closure. Normally you'd use number.hasPrefix by calling it with an argument like this: number.hasPrefix("212"). Without the argument, number.hasPrefix refers to the function hasPrefix called on number and that function has the signature we're looking for: (String) -> Bool. So it can be used as the closure for contains(where:).


        3. So, prefixes.contains(where: number.hasPrefix) takes each prefix from the array and checks if number.hasPrefix(prefix) returns true. If it finds one, it stops searching and returns true. If all of them return false, then prefixes.contains(where:) returns false.







        share|improve this answer






























          3














          This can be done succinctly with:



          if prefixes.contains(where: number.hasPrefix) {
          print("found")
          }


          So, how does this work?




          1. contains(where:) takes a closure that gets called for each element of the prefixes array to decide if the element matches the desired condition. Since prefixes is an array of String, that closure has the signature (String) -> Bool, meaning it takes a String and returns a Bool. contains(where:) will continue to call the given closure for each element in the prefixes array until it gets a true returned, or until it runs out of items in the prefixes array, at which time the answer is false (prefixes doesn't contain an item that matches the condition).


          2. In this case, we are passing the function number.hasPrefix as the closure. Normally you'd use number.hasPrefix by calling it with an argument like this: number.hasPrefix("212"). Without the argument, number.hasPrefix refers to the function hasPrefix called on number and that function has the signature we're looking for: (String) -> Bool. So it can be used as the closure for contains(where:).


          3. So, prefixes.contains(where: number.hasPrefix) takes each prefix from the array and checks if number.hasPrefix(prefix) returns true. If it finds one, it stops searching and returns true. If all of them return false, then prefixes.contains(where:) returns false.







          share|improve this answer




























            3












            3








            3







            This can be done succinctly with:



            if prefixes.contains(where: number.hasPrefix) {
            print("found")
            }


            So, how does this work?




            1. contains(where:) takes a closure that gets called for each element of the prefixes array to decide if the element matches the desired condition. Since prefixes is an array of String, that closure has the signature (String) -> Bool, meaning it takes a String and returns a Bool. contains(where:) will continue to call the given closure for each element in the prefixes array until it gets a true returned, or until it runs out of items in the prefixes array, at which time the answer is false (prefixes doesn't contain an item that matches the condition).


            2. In this case, we are passing the function number.hasPrefix as the closure. Normally you'd use number.hasPrefix by calling it with an argument like this: number.hasPrefix("212"). Without the argument, number.hasPrefix refers to the function hasPrefix called on number and that function has the signature we're looking for: (String) -> Bool. So it can be used as the closure for contains(where:).


            3. So, prefixes.contains(where: number.hasPrefix) takes each prefix from the array and checks if number.hasPrefix(prefix) returns true. If it finds one, it stops searching and returns true. If all of them return false, then prefixes.contains(where:) returns false.







            share|improve this answer















            This can be done succinctly with:



            if prefixes.contains(where: number.hasPrefix) {
            print("found")
            }


            So, how does this work?




            1. contains(where:) takes a closure that gets called for each element of the prefixes array to decide if the element matches the desired condition. Since prefixes is an array of String, that closure has the signature (String) -> Bool, meaning it takes a String and returns a Bool. contains(where:) will continue to call the given closure for each element in the prefixes array until it gets a true returned, or until it runs out of items in the prefixes array, at which time the answer is false (prefixes doesn't contain an item that matches the condition).


            2. In this case, we are passing the function number.hasPrefix as the closure. Normally you'd use number.hasPrefix by calling it with an argument like this: number.hasPrefix("212"). Without the argument, number.hasPrefix refers to the function hasPrefix called on number and that function has the signature we're looking for: (String) -> Bool. So it can be used as the closure for contains(where:).


            3. So, prefixes.contains(where: number.hasPrefix) takes each prefix from the array and checks if number.hasPrefix(prefix) returns true. If it finds one, it stops searching and returns true. If all of them return false, then prefixes.contains(where:) returns false.








            share|improve this answer














            share|improve this answer



            share|improve this answer








            edited Nov 16 '18 at 12:59

























            answered Nov 16 '18 at 12:46









            vacawamavacawama

            96.7k13174198




            96.7k13174198

























                0














                You can try



                if prefixes.filter { number.hasPrefix($0)}.count != 0 {

                }


                Or



                !prefixes.filter { number.hasPrefix($0)}.isEmpty 


                Or



                prefixes.contains { number.hasPrefix($0) }





                share|improve this answer


























                • Even better !prefixes.filter { number.hasPrefix($0)}.isEmpty

                  – EmilioPelaez
                  Nov 15 '18 at 21:34






                • 1





                  You can't use trailing closure in an if without adding some parentheses. You can do if prefixes.contains(where: number.hasPrefix) { though.

                  – vacawama
                  Nov 15 '18 at 22:27






                • 1





                  But this way you gonna iterate over all array, even first element has prefix you're looking for.

                  – user28434
                  Nov 16 '18 at 13:15
















                0














                You can try



                if prefixes.filter { number.hasPrefix($0)}.count != 0 {

                }


                Or



                !prefixes.filter { number.hasPrefix($0)}.isEmpty 


                Or



                prefixes.contains { number.hasPrefix($0) }





                share|improve this answer


























                • Even better !prefixes.filter { number.hasPrefix($0)}.isEmpty

                  – EmilioPelaez
                  Nov 15 '18 at 21:34






                • 1





                  You can't use trailing closure in an if without adding some parentheses. You can do if prefixes.contains(where: number.hasPrefix) { though.

                  – vacawama
                  Nov 15 '18 at 22:27






                • 1





                  But this way you gonna iterate over all array, even first element has prefix you're looking for.

                  – user28434
                  Nov 16 '18 at 13:15














                0












                0








                0







                You can try



                if prefixes.filter { number.hasPrefix($0)}.count != 0 {

                }


                Or



                !prefixes.filter { number.hasPrefix($0)}.isEmpty 


                Or



                prefixes.contains { number.hasPrefix($0) }





                share|improve this answer















                You can try



                if prefixes.filter { number.hasPrefix($0)}.count != 0 {

                }


                Or



                !prefixes.filter { number.hasPrefix($0)}.isEmpty 


                Or



                prefixes.contains { number.hasPrefix($0) }






                share|improve this answer














                share|improve this answer



                share|improve this answer








                edited Nov 15 '18 at 21:44

























                answered Nov 15 '18 at 21:32









                Sh_KhanSh_Khan

                41.8k51326




                41.8k51326













                • Even better !prefixes.filter { number.hasPrefix($0)}.isEmpty

                  – EmilioPelaez
                  Nov 15 '18 at 21:34






                • 1





                  You can't use trailing closure in an if without adding some parentheses. You can do if prefixes.contains(where: number.hasPrefix) { though.

                  – vacawama
                  Nov 15 '18 at 22:27






                • 1





                  But this way you gonna iterate over all array, even first element has prefix you're looking for.

                  – user28434
                  Nov 16 '18 at 13:15



















                • Even better !prefixes.filter { number.hasPrefix($0)}.isEmpty

                  – EmilioPelaez
                  Nov 15 '18 at 21:34






                • 1





                  You can't use trailing closure in an if without adding some parentheses. You can do if prefixes.contains(where: number.hasPrefix) { though.

                  – vacawama
                  Nov 15 '18 at 22:27






                • 1





                  But this way you gonna iterate over all array, even first element has prefix you're looking for.

                  – user28434
                  Nov 16 '18 at 13:15

















                Even better !prefixes.filter { number.hasPrefix($0)}.isEmpty

                – EmilioPelaez
                Nov 15 '18 at 21:34





                Even better !prefixes.filter { number.hasPrefix($0)}.isEmpty

                – EmilioPelaez
                Nov 15 '18 at 21:34




                1




                1





                You can't use trailing closure in an if without adding some parentheses. You can do if prefixes.contains(where: number.hasPrefix) { though.

                – vacawama
                Nov 15 '18 at 22:27





                You can't use trailing closure in an if without adding some parentheses. You can do if prefixes.contains(where: number.hasPrefix) { though.

                – vacawama
                Nov 15 '18 at 22:27




                1




                1





                But this way you gonna iterate over all array, even first element has prefix you're looking for.

                – user28434
                Nov 16 '18 at 13:15





                But this way you gonna iterate over all array, even first element has prefix you're looking for.

                – user28434
                Nov 16 '18 at 13:15











                0














                How about:



                prefixes.forEach { prefix in
                if number.hasPrefix(prefix) {
                print("found")
                }
                }


                You might want to make sure that the prefixes array has no duplicates (= is effectively a set).






                share|improve this answer




























                  0














                  How about:



                  prefixes.forEach { prefix in
                  if number.hasPrefix(prefix) {
                  print("found")
                  }
                  }


                  You might want to make sure that the prefixes array has no duplicates (= is effectively a set).






                  share|improve this answer


























                    0












                    0








                    0







                    How about:



                    prefixes.forEach { prefix in
                    if number.hasPrefix(prefix) {
                    print("found")
                    }
                    }


                    You might want to make sure that the prefixes array has no duplicates (= is effectively a set).






                    share|improve this answer













                    How about:



                    prefixes.forEach { prefix in
                    if number.hasPrefix(prefix) {
                    print("found")
                    }
                    }


                    You might want to make sure that the prefixes array has no duplicates (= is effectively a set).







                    share|improve this answer












                    share|improve this answer



                    share|improve this answer










                    answered Nov 15 '18 at 21:48









                    Jere KäpyahoJere Käpyaho

                    1,1121825




                    1,1121825























                        0














                        If readability is important, you might try this:



                        extension String {
                        func hasAnyPrefix(_ prefixes: [String]) -> Bool {
                        return prefixes.contains { self.hasPrefix($0) }
                        }
                        }

                        if number.hasAnyPrefix(prefixes) {
                        print("found")
                        }





                        share|improve this answer




























                          0














                          If readability is important, you might try this:



                          extension String {
                          func hasAnyPrefix(_ prefixes: [String]) -> Bool {
                          return prefixes.contains { self.hasPrefix($0) }
                          }
                          }

                          if number.hasAnyPrefix(prefixes) {
                          print("found")
                          }





                          share|improve this answer


























                            0












                            0








                            0







                            If readability is important, you might try this:



                            extension String {
                            func hasAnyPrefix(_ prefixes: [String]) -> Bool {
                            return prefixes.contains { self.hasPrefix($0) }
                            }
                            }

                            if number.hasAnyPrefix(prefixes) {
                            print("found")
                            }





                            share|improve this answer













                            If readability is important, you might try this:



                            extension String {
                            func hasAnyPrefix(_ prefixes: [String]) -> Bool {
                            return prefixes.contains { self.hasPrefix($0) }
                            }
                            }

                            if number.hasAnyPrefix(prefixes) {
                            print("found")
                            }






                            share|improve this answer












                            share|improve this answer



                            share|improve this answer










                            answered Nov 16 '18 at 3:42









                            Mike TaverneMike Taverne

                            5,99222138




                            5,99222138






























                                draft saved

                                draft discarded




















































                                Thanks for contributing an answer to Stack Overflow!


                                • Please be sure to answer the question. Provide details and share your research!

                                But avoid



                                • Asking for help, clarification, or responding to other answers.

                                • Making statements based on opinion; back them up with references or personal experience.


                                To learn more, see our tips on writing great answers.




                                draft saved


                                draft discarded














                                StackExchange.ready(
                                function () {
                                StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53328176%2fswift-string-hasprefix-using-an-array-of-strings%23new-answer', 'question_page');
                                }
                                );

                                Post as a guest















                                Required, but never shown





















































                                Required, but never shown














                                Required, but never shown












                                Required, but never shown







                                Required, but never shown

































                                Required, but never shown














                                Required, but never shown












                                Required, but never shown







                                Required, but never shown







                                這個網誌中的熱門文章

                                Tangent Lines Diagram Along Smooth Curve

                                Yusuf al-Mu'taman ibn Hud

                                Zucchini