How to remove special character \u{e2} from string
Thank you every one for your help. You are so kind
I am able to find the invalid character using
phoneNumber?.map{$0.unicodeScalars.allSatisfy{$0.isASCII}}
and it returns
Optional<Array<Bool>>
▿ some : 12 elements
- 0 : false
- 1 : true
- 2 : true
- 3 : true
- 4 : true
- 5 : true
- 6 : true
- 7 : true
- 8 : true
- 9 : true
- 10 : false
- 11 : true
I am able to fix this issue using one line
phoneNumber?.filter{$0.unicodeScalars.allSatisfy{$0.isASCII}}
and Count is 10
using
phoneNumber?.filter{$0.unicodeScalars.allSatisfy{$0.isASCII}}.count
Hope it is helpful to others :)
Swift Switch statement fails to match strings: What could cause this?
I suspect the problem is actually in your getWatchModel
method, specifically in the line:
var machine = CChar()
This allocates a single byte. You need to allocate size
bytes.
Here's one way of doing it:
func getWatchModel() -> String? {
var size: size_t = 0
sysctlbyname("hw.machine", nil, &size, nil, 0)
var machine = [CChar](repeating: 0, count: size)
sysctlbyname("hw.machine", &machine, &size, nil, 0)
return String(cString: machine, encoding: .utf8)
}
I suspect this lead to the String
containing garbage. I'm actually surprised you did not see any crashes.
Switch case with range
This should work.
private func calculateUserScore() -> Int {
let diff = abs(randomNumber - Int(bullsEyeSlider.value))
switch diff {
case 0:
return PointsAward.bullseye.rawValue
case 1..<10:
return PointsAward.almostBullseye.rawValue
case 10..<30:
return PointsAward.close.rawValue
default:
return 0
}
}
It's there in the The Swift Programming Language book under Control Flow -> Interval Matching.
String pattern matching in Swift switch statements
I found the issue. I did not isolate the problem correctly.
The issue was that my source data had a slightly different "-" character which Swift (rightly so) did not consider equal to the condition in the switch cases. I sanitized the inputs and now it works correctly. In the playground I did manually write the input so the issue did not arise.
Thank you so much anyway!
Swift - Multiple Switch Cases
how about :
struct Object{
var type = 1
}
let lowType = min(object1.type,object2.type)
let highType = max(object1.type,object2.type)
switch( lowType, highType )
{
case (1,1):
doSome()
case (1,2):
doSome2()
case (1,3):
doSome3()
...
// you will only need to specify the combinations where the first
// type is less or equal to the other.
}
If you will be doing this often, you could define a minMax function to further reduce the amount of code needed each time:
func minMax<T:Comparable>(_ a:T, _ b:T) ->(T,T)
{ return a<b ? (a,b) : (b,a) }
switch minMax(object1.type,object2.type)
{
case (1,1):
doSome()
case (1,2):
doSome2()
...
note that you can also put each inverted pair in its case statement:
switch(object1.type,object2.type)
{
case (1,1):
doSome()
case (1,2),(2,1):
doSome2()
case (1,3),(3,1):
doSome3()
...
}
[UPDATE]
If you have more than two values to compare in a "permutation insensitive" fashion, you could expand on the minMax() idea by creating variants with more values:
func minToMax<T:Comparable>(_ a:T, _ b:T) -> (T,T)
{ return a<b ? (a,b) : (b,a) }
func minToMax<T:Comparable>(_ a:T, _ b:T, _ c:T) -> (T,T,T)
{ return { ($0[0],$0[1],$0[2]) }([a,b,c].sorted()) }
func minToMax<T:Comparable>(_ a:T, _ b:T, _ c:T, _ d:T) -> (T,T,T,T)
{ return { ($0[0],$0[1],$0[2],$0[3]) }([a,b,c,d].sorted()) }
switch minToMax(object1.type,object2.type,object3.type)
{
case (1,2,3) : doSome1() // permutations of 1,2,3
case (1,2,4) : doSome2() // permutations of 1,2,4
case (1,2,_) : doSome3() // permutations of 1,2,anything else
case (1,5...6,10) : doSome4() // more elaborate permutations
...
}
}
Swift switch case always defaults to the default case
The problem is this line:
guard password.count == 0 else {
The count is never zero. So we fall into this else clause always! That is the .noPass
throw.
throw ValidationError.noPass
But your switch fails to handle that case so it runs the default.
Any way to replace characters on Swift String?
This answer has been updated for Swift 4 & 5. If you're still using Swift 1, 2 or 3 see the revision history.
You have a couple of options. You can do as @jaumard suggested and use replacingOccurrences()
let aString = "This is my string"
let newString = aString.replacingOccurrences(of: " ", with: "+", options: .literal, range: nil)
And as noted by @cprcrack below, the options
and range
parameters are optional, so if you don't want to specify string comparison options or a range to do the replacement within, you only need the following.
let aString = "This is my string"
let newString = aString.replacingOccurrences(of: " ", with: "+")
Or, if the data is in a specific format like this, where you're just replacing separation characters, you can use components()
to break the string into and array, and then you can use the join()
function to put them back to together with a specified separator.
let toArray = aString.components(separatedBy: " ")
let backToString = toArray.joined(separator: "+")
Or if you're looking for a more Swifty solution that doesn't utilize API from NSString, you could use this.
let aString = "Some search text"
let replaced = String(aString.map {
$0 == " " ? "+" : $0
})
Related Topics
Swift 2: Multiline Mkpointannotation
Autoscrolling Infinite Effect in .Linear Type of Icarousel in Swift
Swiftui - Mapkit - Binding Mapkit and Show View on Annotation Callout Buttons
Node.Physicsbody.Joints Downcasting Error
How to Deallocate All References Elements from an Array
Firebase Datadescription Returns Empty Array
How to Delete Firauth Users Using Their User Uid
What Does Cloning a Github Repository Mean
What Does the Underscore in a Function Declaration Do
Ios13 Uialertcontroller with Custom View & Preferredstyle as Actionsheet Grayscale All Colors
How to Move a Model and Generate Its Collision Shape at the Same Time
How to Pass Arguments into a Function with Completion Swift
How to Define an Array of a Particular Enum Case in Swift