This question already has answers here:
How to check if an element is in an array
(18 answers)
How to compare one value against multiple values - Swift
(8 answers)
How to find index of list item in Swift?
(23 answers)
Closed 4 years ago.
Does anyone have an idea how to write the following code in a shortened form?
if self.atPoint(locationUser) == blueMarkArray[0] || self.atPoint(locationUser) == blueMarkArray[1] || self.atPoint(locationUser) == blueMarkArray[2] || self.atPoint(locationUser) == blueMarkArray[3] || self.atPoint(locationUser) == blueMarkArray[4] || self.atPoint(locationUser) == blueMarkArray[5] || self.atPoint(locationUser) == blueMarkArray[6]{
print("its here")
}
Furthermore, I don't want to commit myself to a fixed number of elements in the blueMarkArray array. It should be as variable as possible, because for example it can contain 4 elements, but also 12 elements.
For each answer I am very grateful.
EDIT:
How can you access the found element if I want to write the following: someNode.position = elementOfMarkArray.position
Use array's contains method
if (blueMarkArray.contains(self.atPoint(locationUser))) {
//
}
or, if you need to check only up to index 6 like in your example, use
if (blueMarkArray[0...6].contains(self.atPoint(locationUser))) {
//
}
if you want to get the index of the element, you can use firstIndex of lastIndex methods
if let index = blueMarkArray.firstIndex(of: self.atPoint(locationUser)) {
//
}
You can use the array's method contains:
if blueMarkArray.contains(self.atPoint(locationUser)) {
print("its here")
}
You should simply use the contains method of Array, which will return true if any of the elements of the array equals self.atPoint(locationUser).
if blueMarkArray.contains(self.atPoint(locationUser)) {
print("it's here")
}
If you also need to access the element that matches the object/value you are looking for, you can use first(where:) or firstIndex(of:).
if let location = blueMarkArray.first(where: {$0 == self.atPoint(locationUser)}) {
someNode.position = location.position
}
or
if let locationIndex = blueMarkArray.firstIndex(of: self.atPoint(locationUser)) {
let location = blueMarkArray[locationIndex]
someNode.position = location.position
}
Related
This question already has answers here:
Swift 3 for loop with increment
(5 answers)
Closed 5 years ago.
for example, a Java for-loop:
for(int i=0; i<5; i+=1){
//
}
convert to Swift
for index in 0..<5 {
}
but what if i+=2?
I'm new to Swift.. Maybe it's a stupid question, but will be appreciate if you answer it, thx! :-)
Check this
for index in stride(from: 0, to: 5, by: 2){
print(index)
}
You can use this way as well.
var first = 0
var last = 10
var add = 2
for i in sequence(first: first, next: { $0 + add })
.prefix(while: { $0 <= last }) {
print(i)
}
Output will be: 0,2,4,6,8,10
In case if your for loop was doing something more complex than adding constant value to index each iteration you may use something like that:
Assuming you have this for loop:
for(index = initial; condition(index); mutation(index)){
//
}
Where
initial — initial value constant of type T
condition — function (T) -> Bool, that checks if loop should end
mutation — function (T) -> T, that changes index value each iteration
Then it will be:
for index in sequence(first: initial, next: { current in
let next = mutation(current)
return condition(next) ? next : nil
}) {
//
}
This question already has answers here:
Separating multiple if conditions with commas in Swift
(6 answers)
Closed 5 years ago.
I've recently come across this type of scenario using if/let and understand what it does thanks to this post. To my understanding, both conditions need to be met before the proceeding block is executed. I now have come to a point where I've seen it in a regular conditional statement:
if existingTextHasDecimalSeparator != nil, replacementTextHasDecimalSeparator != nil {
return false
} else {
return true
}
What's the difference between doing the above and simply using && as seen below?:
if existingTextHasDecimalSeparator != nil && replacementTextHasDecimalSeparator != nil {
return false
} else {
return true
}
There does not appear to be a difference between using && for grouping conditionals and using commas. I too have so far only seen it used with optional binding, but apparently it also works for regular conditionals, as the following snippet works fine.
let bool1 = true;
let bool2 = true;
if bool1 , bool2 {
print("true");
} else {
print("false")
}
The comma is used when optional binding with boolean conditions, for example if let a = a, a.isValid() whereas && is a typical AND operator
I'm new in IOS programming. I have a question, how to get all value in array except x value. Let say i have array like below :
let array : [Any] = [1,2,3,4,5,6,7,8,9,0,11,22,33,44,55,66,77,200]
how to print all value except 1 and 2.
I have read this , its using filter and i try it with playground but i still not have the right value. Any answer will helpfull for me. Thanks in advance .
I don't know why you have defined the array as [Any] so I just removed that and the array is:-
let array = [1,2,3,4,5,6,7,8,9,0,11,22,33,44,55,66,77,200]
Next you can use filter as follows:-
let filtered = array.filter { (element) -> Bool in
return element != 1 && element != 2
}
You can test this out in the playground, it will print all values except 1 & 2
You can also use some syntactical sugar for filter as follows:-
array.filter({ return $0 != 1 && $0 != 2 })
And since the closure is a trailing argument, you can also separate it from the arguments as follows:-
array.filter { return $0 != 1 && $0 != 2 }
Another way to do this would be
let filterTheseOut = [1,2]
let anotherWay = array.filter { !filterTheseOut.contains($0) }
So here you can basically add all the elements to be filtered out in a separate array
You can do it like this
let array : [Int] = [1,2,3,4,5,6,7,8,9,0,11,22,33,44,55,66,77,200]
print(array.filter { $0 != 1 && $0 != 2 } )
or if you will have more than 1 or 2 values you can put them into array
let array : [Int] = [1,2,3,4,5,6,7,8,9,0,11,22,33,44,55,66,77,200]
let unwantedValues = [1,2]
print(array.filter { unwantedValues.contains($0) == false } )
Next time please paste your code, it will be easier to tell you what you're doing wrong, then giving you ready solution.
No need for filter use this:
for i in array {
if i != 1 && i != 2 {
print i
}
}
// This will print all values except 1 and 2
This question already has answers here:
Can I use the range operator with if statement in Swift?
(6 answers)
Closed 6 years ago.
I need to code in swift for 'if numbers are between 1 to 5'
I tried this but it's not working.
if myPercent == (1 ... 5) {
let numberGroup = 1
How do I fix this?
Use contains:
if (1...5).contains(myPercent) {
...
}
contains seems to be the basic manner to work with range.
Here are some additions...
Use pattern matching operator:
if 1...5 ~= myPercent {
//...
}
Use if-case:
if case 1...5 = myPercent {
//...
}
You could just use two conditions to check whether it's in bounds:
if myPercent >= 1 && myPercent <= 5 {
...
}
Consider using an extension combined with a switch statement:
extension Int {
func isBetween(range:Range<Int>) -> Bool {
switch self {
case range:
return true
default:
return false
}
}
}
This makes implementation far easier:
5.isBetween(1...5) // true
6.isBetween(1...5) // false
Note that for this to work in Xcode 8 / Swift 3 you must use the half-open range operator:
5.isBetween(1..<6) // true
6.isBetween(1..<6) // false
So in your instance:
if myPercent.isBetween(1..<6) {
let numberGroup = 1
}
Or perhaps:
let numberGroup = myPercent.isBetween(range: 1..<6) ? 1 : 0
This question already has answers here:
What is the best way to determine if a string contains a character from a set in Swift
(11 answers)
Closed 7 years ago.
I'm trying to check whether a specific string contains letters or not.
So far I've come across NSCharacterSet.letterCharacterSet() as a set of letters, but I'm having trouble checking whether a character in that set is in the given string. When I use this code, I get an error stating:
'Character' is not convertible to 'unichar'
For the following code:
for chr in input{
if letterSet.characterIsMember(chr){
return "Woah, chill out!"
}
}
You can use NSCharacterSet in the following way :
let letters = NSCharacterSet.letters
let phrase = "Test case"
let range = phrase.rangeOfCharacter(from: characterSet)
// range will be nil if no letters is found
if let test = range {
println("letters found")
}
else {
println("letters not found")
}
Or you can do this too :
func containsOnlyLetters(input: String) -> Bool {
for chr in input {
if (!(chr >= "a" && chr <= "z") && !(chr >= "A" && chr <= "Z") ) {
return false
}
}
return true
}
In Swift 2:
func containsOnlyLetters(input: String) -> Bool {
for chr in input.characters {
if (!(chr >= "a" && chr <= "z") && !(chr >= "A" && chr <= "Z") ) {
return false
}
}
return true
}
It's up to you, choose a way. I hope this help you.
You should use the Strings built in range functions with NSCharacterSet rather than roll your own solution. This will give you a lot more flexibility too (like case insensitive search if you so desire).
let str = "Hey this is a string"
let characterSet = NSCharacterSet(charactersInString: "aeiou")
if let _ = str.rangeOfCharacterFromSet(characterSet, options: .CaseInsensitiveSearch) {
println("true")
}
else {
println("false")
}
Substitute "aeiou" with whatever letters you're looking for.
A less flexible, but fun swift note all the same, is that you can use any of the functions available for Sequences. So you can do this:
contains("abc", "c")
This of course will only work for individual characters, and is not flexible and not recommended.
The trouble with .characterIsMember is that it takes a unichar (a typealias for UInt16).
If you iterate your input using the utf16 view of the string, it will work:
let set = NSCharacterSet.letterCharacterSet()
for chr in input.utf16 {
if set.characterIsMember(chr) {
println("\(chr) is a letter")
}
}
You can also skip the loop and use the contains algorithm if you only want to check for presence/non-presence:
if contains(input.utf16, { set.characterIsMember($0) }) {
println("contains letters")
}