Swift String hasPrefix Using an Array of Strings
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
add a comment |
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
1
The answer to your question is in @vacawama's commentprefixes.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
add a comment |
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
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
swift
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 commentprefixes.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
add a comment |
1
The answer to your question is in @vacawama's commentprefixes.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
add a comment |
4 Answers
4
active
oldest
votes
This can be done succinctly with:
if prefixes.contains(where: number.hasPrefix) {
print("found")
}
So, how does this work?
contains(where:)takes a closure that gets called for each element of theprefixesarray to decide if the element matches the desired condition. Sinceprefixesis an array ofString, that closure has the signature(String) -> Bool, meaning it takes aStringand returns aBool.contains(where:)will continue to call the given closure for each element in theprefixesarray until it gets atruereturned, or until it runs out of items in theprefixesarray, at which time the answer isfalse(prefixesdoesn't contain an item that matches the condition).In this case, we are passing the function
number.hasPrefixas the closure. Normally you'd usenumber.hasPrefixby calling it with an argument like this:number.hasPrefix("212"). Without the argument,number.hasPrefixrefers to the functionhasPrefixcalled onnumberand that function has the signature we're looking for:(String) -> Bool. So it can be used as the closure forcontains(where:).So,
prefixes.contains(where: number.hasPrefix)takes eachprefixfrom the array and checks ifnumber.hasPrefix(prefix)returnstrue. If it finds one, it stops searching and returnstrue. If all of them returnfalse, thenprefixes.contains(where:)returns false.
add a comment |
You can try
if prefixes.filter { number.hasPrefix($0)}.count != 0 {
}
Or
!prefixes.filter { number.hasPrefix($0)}.isEmpty
Or
prefixes.contains { number.hasPrefix($0) }
Even better!prefixes.filter { number.hasPrefix($0)}.isEmpty
– EmilioPelaez
Nov 15 '18 at 21:34
1
You can't use trailing closure in anifwithout adding some parentheses. You can doif 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
add a comment |
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).
add a comment |
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")
}
add a comment |
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
});
}
});
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
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
This can be done succinctly with:
if prefixes.contains(where: number.hasPrefix) {
print("found")
}
So, how does this work?
contains(where:)takes a closure that gets called for each element of theprefixesarray to decide if the element matches the desired condition. Sinceprefixesis an array ofString, that closure has the signature(String) -> Bool, meaning it takes aStringand returns aBool.contains(where:)will continue to call the given closure for each element in theprefixesarray until it gets atruereturned, or until it runs out of items in theprefixesarray, at which time the answer isfalse(prefixesdoesn't contain an item that matches the condition).In this case, we are passing the function
number.hasPrefixas the closure. Normally you'd usenumber.hasPrefixby calling it with an argument like this:number.hasPrefix("212"). Without the argument,number.hasPrefixrefers to the functionhasPrefixcalled onnumberand that function has the signature we're looking for:(String) -> Bool. So it can be used as the closure forcontains(where:).So,
prefixes.contains(where: number.hasPrefix)takes eachprefixfrom the array and checks ifnumber.hasPrefix(prefix)returnstrue. If it finds one, it stops searching and returnstrue. If all of them returnfalse, thenprefixes.contains(where:)returns false.
add a comment |
This can be done succinctly with:
if prefixes.contains(where: number.hasPrefix) {
print("found")
}
So, how does this work?
contains(where:)takes a closure that gets called for each element of theprefixesarray to decide if the element matches the desired condition. Sinceprefixesis an array ofString, that closure has the signature(String) -> Bool, meaning it takes aStringand returns aBool.contains(where:)will continue to call the given closure for each element in theprefixesarray until it gets atruereturned, or until it runs out of items in theprefixesarray, at which time the answer isfalse(prefixesdoesn't contain an item that matches the condition).In this case, we are passing the function
number.hasPrefixas the closure. Normally you'd usenumber.hasPrefixby calling it with an argument like this:number.hasPrefix("212"). Without the argument,number.hasPrefixrefers to the functionhasPrefixcalled onnumberand that function has the signature we're looking for:(String) -> Bool. So it can be used as the closure forcontains(where:).So,
prefixes.contains(where: number.hasPrefix)takes eachprefixfrom the array and checks ifnumber.hasPrefix(prefix)returnstrue. If it finds one, it stops searching and returnstrue. If all of them returnfalse, thenprefixes.contains(where:)returns false.
add a comment |
This can be done succinctly with:
if prefixes.contains(where: number.hasPrefix) {
print("found")
}
So, how does this work?
contains(where:)takes a closure that gets called for each element of theprefixesarray to decide if the element matches the desired condition. Sinceprefixesis an array ofString, that closure has the signature(String) -> Bool, meaning it takes aStringand returns aBool.contains(where:)will continue to call the given closure for each element in theprefixesarray until it gets atruereturned, or until it runs out of items in theprefixesarray, at which time the answer isfalse(prefixesdoesn't contain an item that matches the condition).In this case, we are passing the function
number.hasPrefixas the closure. Normally you'd usenumber.hasPrefixby calling it with an argument like this:number.hasPrefix("212"). Without the argument,number.hasPrefixrefers to the functionhasPrefixcalled onnumberand that function has the signature we're looking for:(String) -> Bool. So it can be used as the closure forcontains(where:).So,
prefixes.contains(where: number.hasPrefix)takes eachprefixfrom the array and checks ifnumber.hasPrefix(prefix)returnstrue. If it finds one, it stops searching and returnstrue. If all of them returnfalse, thenprefixes.contains(where:)returns false.
This can be done succinctly with:
if prefixes.contains(where: number.hasPrefix) {
print("found")
}
So, how does this work?
contains(where:)takes a closure that gets called for each element of theprefixesarray to decide if the element matches the desired condition. Sinceprefixesis an array ofString, that closure has the signature(String) -> Bool, meaning it takes aStringand returns aBool.contains(where:)will continue to call the given closure for each element in theprefixesarray until it gets atruereturned, or until it runs out of items in theprefixesarray, at which time the answer isfalse(prefixesdoesn't contain an item that matches the condition).In this case, we are passing the function
number.hasPrefixas the closure. Normally you'd usenumber.hasPrefixby calling it with an argument like this:number.hasPrefix("212"). Without the argument,number.hasPrefixrefers to the functionhasPrefixcalled onnumberand that function has the signature we're looking for:(String) -> Bool. So it can be used as the closure forcontains(where:).So,
prefixes.contains(where: number.hasPrefix)takes eachprefixfrom the array and checks ifnumber.hasPrefix(prefix)returnstrue. If it finds one, it stops searching and returnstrue. If all of them returnfalse, thenprefixes.contains(where:)returns false.
edited Nov 16 '18 at 12:59
answered Nov 16 '18 at 12:46
vacawamavacawama
96.7k13174198
96.7k13174198
add a comment |
add a comment |
You can try
if prefixes.filter { number.hasPrefix($0)}.count != 0 {
}
Or
!prefixes.filter { number.hasPrefix($0)}.isEmpty
Or
prefixes.contains { number.hasPrefix($0) }
Even better!prefixes.filter { number.hasPrefix($0)}.isEmpty
– EmilioPelaez
Nov 15 '18 at 21:34
1
You can't use trailing closure in anifwithout adding some parentheses. You can doif 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
add a comment |
You can try
if prefixes.filter { number.hasPrefix($0)}.count != 0 {
}
Or
!prefixes.filter { number.hasPrefix($0)}.isEmpty
Or
prefixes.contains { number.hasPrefix($0) }
Even better!prefixes.filter { number.hasPrefix($0)}.isEmpty
– EmilioPelaez
Nov 15 '18 at 21:34
1
You can't use trailing closure in anifwithout adding some parentheses. You can doif 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
add a comment |
You can try
if prefixes.filter { number.hasPrefix($0)}.count != 0 {
}
Or
!prefixes.filter { number.hasPrefix($0)}.isEmpty
Or
prefixes.contains { number.hasPrefix($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) }
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 anifwithout adding some parentheses. You can doif 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
add a comment |
Even better!prefixes.filter { number.hasPrefix($0)}.isEmpty
– EmilioPelaez
Nov 15 '18 at 21:34
1
You can't use trailing closure in anifwithout adding some parentheses. You can doif 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
add a comment |
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).
add a comment |
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).
add a comment |
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).
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).
answered Nov 15 '18 at 21:48
Jere KäpyahoJere Käpyaho
1,1121825
1,1121825
add a comment |
add a comment |
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")
}
add a comment |
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")
}
add a comment |
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")
}
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")
}
answered Nov 16 '18 at 3:42
Mike TaverneMike Taverne
5,99222138
5,99222138
add a comment |
add a comment |
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.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
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
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
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
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