Swift || do we possible to detect how many spaces of empty string have? - swift

lets say we have an extension of String:
extension String {
var textBeCleared: Bool {
// how we write here
}
}
then:
var demo1 = "" // no space over here
demo.textBeCleared // true
var demo2 = " " // type one space over here
demo.textBeCleared // false
because I got a sticky issue is: I have a save button at bottom of a text field, save button only displays when removing all text contents in the text field, like demo1. but if type more space over here, like demo2, save button will be hidden.

User filter for this purpose. It will filter each char in the string and you will get your expected result.
let inputString1 = " "
let inputString2 = ""
let inputString3 = "a"
let spacesCount1 = inputString1.filter { $0 == " " }
print(spacesCount1.count)
let spacesCount2 = inputString2.filter { $0 == " " }
print(spacesCount2.count)
let spacesCount3 = inputString3.filter { $0 == " " }
print(spacesCount3.count)
Output
3
0
0

thanks guys, I managed solved this by following code
let inputString1 = " "
let inputString2 = ""
let inputString3 = "a"
extension String {
var textBeCleared: Bool {
!self.contains(" ") && allSatisfy { $0.isWhitespace }
}
}
inputString1.textBeCleared // false
inputString2.textBeCleared // true
inputString3.textBeCleared // false

you could try this:
extension String {
var textBeCleared: Bool {
self.isEmpty
}
}
var demo1 = "" // no space over here
var demo2 = " " // type one space over here
print(" demo1.textBeCleared: \(demo1.textBeCleared) ") // true
print(" demo2.textBeCleared: \(demo2.textBeCleared) ") // false

Related

Highlight a specific part of the text in SwiftUI

Hello I'm new to Swift and am using SwiftUI for my project where I download some weather data and I display it in the ContentView().
I would like to highlight some part of the Text if it contains some specific word, but I don't have any idea how to start.
In ContentView(), I have tried to set a function receiving the string downloaded from web and return a string. I believe this is wrong, because SwiftUI does not apply the modifiers at the all for the Text.
For example, in my ContentView() I would like the word thunderstorm to have the .bold() modifier:
struct ContentView: View {
let testo : String = "There is a thunderstorm in the area"
var body: some View {
Text(highlight(str: testo))
}
func highlight(str: String) -> String {
let textToSearch = "thunderstorm"
var result = ""
if str.contains(textToSearch) {
let index = str.startIndex
result = String( str[index])
}
return result
}
}
If that requires just simple word styling then here is possible solution.
Tested with Xcode 11.4 / iOS 13.4
struct ContentView: View {
let testo : String = "There is a thunderstorm in the area. Added some testing long text to demo that wrapping works correctly!"
var body: some View {
hilightedText(str: testo, searched: "thunderstorm")
.multilineTextAlignment(.leading)
}
func hilightedText(str: String, searched: String) -> Text {
guard !str.isEmpty && !searched.isEmpty else { return Text(str) }
var result: Text!
let parts = str.components(separatedBy: searched)
for i in parts.indices {
result = (result == nil ? Text(parts[i]) : result + Text(parts[i]))
if i != parts.count - 1 {
result = result + Text(searched).bold()
}
}
return result ?? Text(str)
}
}
Note: below is previously used function, but as commented by #Lkabo it has limitations on very long strings
func hilightedText(str: String) -> Text {
let textToSearch = "thunderstorm"
var result: Text!
for word in str.split(separator: " ") {
var text = Text(word)
if word == textToSearch {
text = text.bold()
}
result = (result == nil ? text : result + Text(" ") + text)
}
return result ?? Text(str)
}
iOS 13, Swift 5. There is a generic solution described in this medium article. Using it you can highlight any text anywhere with the only catch being it cannot be more then 64 characters in length, since it using bitwise masks.
https://medium.com/#marklucking/an-interesting-challenge-with-swiftui-9ebb26e77376
This is the basic code in the article.
ForEach((0 ..< letter.count), id: \.self) { column in
Text(letter[column])
.foregroundColor(colorCode(gate: Int(self.gate), no: column) ? Color.black: Color.red)
.font(Fonts.futuraCondensedMedium(size: fontSize))
}
And this one to mask the text...
func colorCode(gate:Int, no:Int) -> Bool {
let bgr = String(gate, radix:2).pad(with: "0", toLength: 16)
let bcr = String(no, radix:2).pad(with: "0", toLength: 16)
let binaryColumn = 1 << no - 1
let value = UInt64(gate) & UInt64(binaryColumn)
let vr = String(value, radix:2).pad(with: "0", toLength: 16)
print("bg ",bgr," bc ",bcr,vr)
return value > 0 ? true:false
}
You can concatenate with multiple Text Views.
import SwiftUI
import PlaygroundSupport
struct ContentView: View {
var body: some View{
let testo : String = "There is a thunderstorm in the area"
let stringArray = testo.components(separatedBy: " ")
let stringToTextView = stringArray.reduce(Text(""), {
if $1 == "thunderstorm" {
return $0 + Text($1).bold() + Text(" ")
} else {
return $0 + Text($1) + Text(" ")
}
})
return stringToTextView
}
}
PlaygroundPage.current.setLiveView(ContentView())
If you are targeting iOS15 / macOS12 and above, you can use AttributedString. For example:
private struct HighlightedText: View {
let text: String
let highlighted: String
var body: some View {
Text(attributedString)
}
private var attributedString: AttributedString {
var attributedString = AttributedString(text)
if let range = attributedString.range(of: highlighted)) {
attributedString[range].backgroundColor = .yellow
}
return attributedString
}
}
If you want your match to be case insensitive, you could replace the line
if let range = attributedString.range(of: highlighted)
with
if let range = AttributedString(text.lowercased()).range(of: highlighted.lowercased())
The answer of #Asperi works well. Here is a modified variant with a search by array of single words:
func highlightedText(str: String, searched: [String]) -> Text {
guard !str.isEmpty && !searched.isEmpty else { return Text(str) }
var result: Text!
let parts = str.components(separatedBy: " ")
for part_index in parts.indices {
result = (result == nil ? Text("") : result + Text(" "))
if searched.contains(parts[part_index].trimmingCharacters(in: .punctuationCharacters)) {
result = result + Text(parts[part_index])
.bold()
.foregroundColor(.red)
}
else {
result = result + Text(parts[part_index])
}
}
return result ?? Text(str)
}
Usage example:
let str: String = "There is a thunderstorm in the area. Added some testing long text to demo that wrapping works correctly!"
let searched: [String] = ["thunderstorm", "wrapping"]
highlightedText(str: str, searched: searched)
.padding()
.background(.yellow)
You can also make AttributedString with markdown this way
do {
return try AttributedString(markdown: foreignSentence.replacing(word.foreign, with: "**\(word.foreign)**"))
} catch {
return AttributedString(foreignSentence)
}
and just use Text
Text(foreignSentenceMarkdown)

In Swift How do I iterate over an array getting 2 variables when each pair of elements is a String? and a String

I want to iterate over an array String?, String repeated pair but I cannot form the "for case let (a,b) in array" correctly.
The best I have come up with is to create a temp struct of {String?, String} and create an array of the temp structs and then iterate it but I would like to skip this step.
Below is the basic example with the last for loop showing the error Xcode reports.
class Foo {
var s1: String?
var s2: String?
var s3: String?
}
let foo = Foo()
foo.s1="Test1"
foo.s2=nil
foo.s3="Test3"
let fooArray = [foo.s1, ", ", foo.s2, "; ", foo.s3,"."]
let fooArray1 = [foo.s1,foo.s2, foo.s3]
var text:String = ""
for case let prop? in fooArray1 {
text = text + prop + " / "
}
print(text)
// The above works but now I want to use a different separator
//base on the property name
text=""
for case let (prop, sep) in fooArray { // Error <= Expression Type
// [String?] is ambiguous without more context
text = text + prop + sep
}
print(text)
Here is what I have come up with
struct temp {
var prop:String?
var sep:String
init(_ prop:String?, _ sep:String) {
self.prop=prop
self.sep=sep
}
let ary:[temp] = [ temp(foo.s1,", "), temp(foo.s2,"; "), temp(foo.s3,".") ]
text = ""
for a in ary {
if let p = a.prop {
text = text + p + a.sep
}
}
print (text)
is there another way just using the for loop
for (a,b) in fooArray {
...
}
As noted by #RJE, the inferred type of fooArray, as defined in your code, is [String?].
Here is one way to make it work:
class Foo {
var s1: String?
var s2: String?
var s3: String?
}
let foo = Foo()
foo.s1 = "Test1"
foo.s2 = nil
foo.s3 = "Test3"
let fooArray1 = [foo.s1, foo.s2, foo.s3]
let separators = [", ", "; ", "."]
var text = ""
for i in fooArray1.indices {
if let p = fooArray1[i] {
text = text + p + separators[i]
}
}
print (text) //Test1, Test3.
Or
let zipped = zip(fooArray1, separators)
let text = zipped.map { tuple -> String in
if case let (x?, y) = tuple {
return x + y
} else {
return ""
}
}.joined()
print (text) //Test1,Test3.
Or
let fooArray = [foo.s1, ", ", foo.s2, "; ", foo.s3, "."]
var text = ""
var step = 1
var index = 0
while index < fooArray.count {
if let str = fooArray[index] {
step = 1
text += str
} else {
step = 2
}
index += step
}
print(text) //Test1, Test3.
It would be better to define the initializer this way :
class Foo {
var s1: String?
var s2: String?
var s3: String?
init(s1: String?, s2: String?, s3: String?) {
self.s1 = s1
self.s2 = s2
self.s3 = s3
}
}
let foo = Foo(s1: "Test1", s2: nil, s3: "Test3")
P.S: The desired output seems to be more appropriate for a description property of the Foo class.
Thanks for the answer I was hoping through this question to get a better understanding of how to use [for] parameters. But the while solution is the solution I would probably use with the following modifications
text = ""
var index = 0
while index < fooArray.count {
if let prop = fooArray[index] {
index += 1
let sep = fooArray[index]!
index += 1
text = text + prop + sep
} else {
index += 2
}
}

Task from the interview. How we would solve it?

Convert String in this way
let initialString = "atttbcdddd"
// result must be like this "at3bcd4"
But repetition must be more than 2. For example, if we have "aa" the result will be "aa", but if we have "aaa", the result will be "a3"
One more example:
let str = "aahhhgggg"
//result "aah3g4"
My try:
func encrypt(_ str: String) -> String {
let char = str.components(separatedBy: "t") //must input the character
var count = char.count - 1
var string = ""
string.append("t\(count)")
return string
}
if i input "ttttt" it will return "t5" but i should input the character
What you are looking for is the “Run-length encoding”. Note that this is not an encryption!
Here is a possible implementation (explanations inline):
func runLengthEncode(_ str: String) -> String {
var result = ""
var pos = str.startIndex // Start index of current run
while pos != str.endIndex {
let char = str[pos]
// Find index of next run (or `endIndex` if there is none):
let next = str[pos...].firstIndex(where: { $0 != char }) ?? str.endIndex
// Compute the length of the current run:
let length = str.distance(from: pos, to: next)
// Append compressed output to the result:
result.append(length <= 2 ? String(repeating: char, count: length) : "\(char)\(length)")
pos = next // ... and continue with next run
}
return result
}
Examples:
print(runLengthEncode("atttbcdddd")) // at3bcd4
print(runLengthEncode("aahhhgggg")) // aah3g4
print(runLengthEncode("abbbaaa")) // ab3a3
Checkout this :
func convertString(_ input : String) -> String {
let allElements = Array(input)
let uniqueElements = Array(NSOrderedSet(array: allElements)) as! [Character]
var outputString = ""
for uniqueChar in uniqueElements {
var count = 0
for char in allElements {
if char == uniqueChar {
count+=1
}
}
if count > 2 {
outputString += "\(uniqueChar)\(count)"
} else if count == 2 {
outputString += "\(uniqueChar)\(uniqueChar)"
} else {
outputString += "\(uniqueChar)"
}
}
return outputString
}
Input : convertString("atttbcdddd")
Output : at3bcd4
I've tried it before for one of the interview and also I think you too :). However, very simple way to do it is just go through step by step of code.
let initialString = "atttbcdddd"
var previousChar: Character = " "
var output = ""
var i = 1 // Used to count the repeated charaters
var counter = 0 // To check the last character has been reached
//Going through each character
for char in initialString {
//Increase the characters counter to check the last element has been reached. If it is, add the character to output.
counter += 1
if previousChar == char { i += 1 }
else {
output = output + (i == 1 ? "\(previousChar)" : "\(previousChar)\(i)")
i = 1
}
if initialString.count == counter {
output = output + (i == 1 ? "\(previousChar)" : "\(previousChar)\(i)")
}
previousChar = char
}
let finalOutput = output.trimmingCharacters(in: .whitespacesAndNewlines)
print(finalOutput)
let initialString = "atttbcdddd"
let myInitialString = initialString + " "
var currentLetter: Character = " "
var currentCount = 1
var answer = ""
for (_, char) in myInitialString.enumerated(){
if char == currentLetter {
currentCount += 1
} else {
if currentCount > 1 {
answer += String(currentCount)
}
answer += String(char)
currentCount = 1
currentLetter = char
}
}
print(answer)
Use reduce here.
func exp(_ s : String, _ term: String) -> String{ //term_inator: Any Char not in the Sequence.
guard let first = s.first else {return ""}
return """
\(s.dropFirst().appending(term).reduce(("\(first)",1)){ r, c in
let t = c == r.0.last!
let tc = t ? r.1 : 0
let tb = t ? "" : "\(c)"
let ta = t ? "" : r.1 > 2 ? "\(r.1)" : r.1 == 2 ? "\(r.0.last!)" : ""
return (r.0 + ta + tb, tc + 1)
}.0.dropLast())
"""}
print(exp(initialString, " "))
let initialString = "abbbaaa" // ab3a3
let initialString = "aahhhgggg" // aah3g4
let initialString = "aabbaa" // aabbaa

How to remove duplicate characters from a string in Swift

ruby has the function string.squeeze, but I can't seem to find a swift equivalent.
For example I want to turn bookkeeper -> bokepr
Is my only option to create a set of the characters and then pull the characters from the set back to a string?
Is there a better way to do this?
Edit/update: Swift 4.2 or later
You can use a set to filter your duplicated characters:
let str = "bookkeeper"
var set = Set<Character>()
let squeezed = str.filter{ set.insert($0).inserted }
print(squeezed) // "bokepr"
Or as an extension on RangeReplaceableCollection which will also extend String and Substrings as well:
extension RangeReplaceableCollection where Element: Hashable {
var squeezed: Self {
var set = Set<Element>()
return filter{ set.insert($0).inserted }
}
}
let str = "bookkeeper"
print(str.squeezed) // "bokepr"
print(str[...].squeezed) // "bokepr"
I would use this piece of code from another answer of mine, which removes all duplicates of a sequence (keeping only the first occurrence of each), while maintaining order.
extension Sequence where Iterator.Element: Hashable {
func unique() -> [Iterator.Element] {
var alreadyAdded = Set<Iterator.Element>()
return self.filter { alreadyAdded.insert($0).inserted }
}
}
I would then wrap it with some logic which turns a String into a sequence (by getting its characters), unqiue's it, and then restores that result back into a string:
extension String {
func uniqueCharacters() -> String {
return String(self.characters.unique())
}
}
print("bookkeeper".uniqueCharacters()) // => "bokepr"
Here is a solution I found online, however I don't think it is optimal.
func removeDuplicateLetters(_ s: String) -> String {
if s.characters.count == 0 {
return ""
}
let aNum = Int("a".unicodeScalars.filter{$0.isASCII}.map{$0.value}.first!)
let characters = Array(s.lowercased().characters)
var counts = [Int](repeatElement(0, count: 26))
var visited = [Bool](repeatElement(false, count: 26))
var stack = [Character]()
var i = 0
for character in characters {
if let num = asciiValueOfCharacter(character) {
counts[num - aNum] += 1
}
}
for character in characters {
if let num = asciiValueOfCharacter(character) {
i = num - aNum
counts[i] -= 1
if visited[i] {
continue
}
while !stack.isEmpty, let peekNum = asciiValueOfCharacter(stack.last!), num < peekNum && counts[peekNum - aNum] != 0 {
visited[peekNum - aNum] = false
stack.removeLast()
}
stack.append(character)
visited[i] = true
}
}
return String(stack)
}
func asciiValueOfCharacter(_ character: Character) -> Int? {
let value = String(character).unicodeScalars.filter{$0.isASCII}.first?.value ?? 0
return Int(value)
}
Here is one way to do this using reduce(),
let newChar = str.characters.reduce("") { partial, char in
guard let _ = partial.range(of: String(char)) else {
return partial.appending(String(char))
}
return partial
}
As suggested by Leo, here is a bit shorter version of the same approach,
let newChar = str.characters.reduce("") { $0.range(of: String($1)) == nil ? $0.appending(String($1)) : $0 }
Just Another solution
let str = "Bookeeper"
let newChar = str.reduce("" , {
if $0.contains($1) {
return "\($0)"
} else {
return "\($0)\($1)"
}
})
print(str.replacingOccurrences(of: " ", with: ""))
Use filter and contains to remove duplicate values
let str = "bookkeeper"
let result = str.filter{!result.contains($0)}
print(result) //bokepr

Check if string has a space

I have a string that contains a url. I am trying to check if the url has a space which is invalid.
let url = "http://www.example.com/images/pretty pic.png"
As you can see in this example, there is a space between pretty and pic. Thanks.
Another alternative: check if the set of characters to the string contain a whitespace
let url = "http://www.example.com/images/pretty pic.png"
url.characters.contains(" ") // true
let url = "http://www.example.com/images/prettypic.png"
url.characters.contains(" ") // false
let url = "http://www.example.com/images/pretty pic.png"
let whiteSpace = " "
if let hasWhiteSpace = url.rangeOfString(whiteSpace) {
print ("has whitespace")
} else {
print("no whitespace")
}
Use simple indexOf to find the space.
function hasWhiteSpace(s) {
return s.indexOf(' ') >= 0;
}
extension on String which returns bool would be more elegant solution here
extension String {
public var hasWhiteSpace: Bool {
return self.contains(" ")
}
}
For Swift 5
var string = "Hi "
if string.contains(" "){
print("Has space")
}else{
print("Does not have space")
}