How to trim several textfield in swift at once? - ios

I have several textfield in a page. Currently i'm trimming every textfield one by one like code below.
public struct CustomerAddressDetail: Encodable {
public var fullname: String?
public var identifierNumber: String?
}
var customerInfoDetail = CustomerInfoDetail()
customerInfoDetail.fullname = itemsInput[0][0].value?.trimmingCharacters(in: .whitespaces) ?? ""
customerInfoDetail.identifierNumber = itemsInput[0][1].value?.trimmingCharacters(in: .whitespaces) ?? ""
I try to trim multiple value at once. Because it looks like a bad way to trim it one by one
Is it really like that ? Or is there any better way to trim multiple item ?

It looks bad to you because you have duplicate code. A nicer way to it is using iteration or map like this:
let stringlist: [String] = ["a ", "b ", "c "]
let trimmedlist = stringlist.map { s in
return s.trimmingCharacters(in: .whitespaces)
}

Related

SwiftUI Text and LocalizedStringKey with parameter

I am trying to add a SwiftUI localized Text with parameter. However in the whole app we use a wrapper around localization keys so we have something like this:
static let helloWorldText = NSLocalizedString("helloWorldText", comment: "")
with usage
label.text = LocalizationWrapper.helloWorldText
or
Text(LocalizationWrapper.helloWorldText)
and it works fine.
Then when it comes to adding a localized text with parameter it doesn't seems to work.
So I have a key "helloWorld %#"
and I have a static let helloWorldWithParameter = NSLocalizedString("helloWorld %#", comment: "")
now i tried to do this:
Text("\(LocalizationWrapper.helloWorldWithParameter) \(name)")
Text(LocalizedStringKey(LocalizationWrapper.helloWorldWithParameter + " " + name))
Text(LocalizationWrapper.helloWorldWithParameter + " " + name)
none of them works, however Text("helloWorld \(name)") works just fine.
Then i tried to remove NSLocalizedString leaving only LocalizationWrapper.helloWorldWithParameter as a clean string but it allso didn't do a thing
How can I make this work? I seen THIS but it is kind of dirty.
Use this extension
extension String {
public func localized(with arguments: [CVarArg]) -> String {
return String(format: NSLocalizedString(self, comment: ""), locale: nil, arguments: arguments)
}
}
Usage :
Text(LocalizationWrapper.helloWorldWithParameter.localized(with: [name]))
Also, This approach is correct
static func helloWithParameter(parameter: String) -> LocalizedStringKey {
return "helloWorld \(parameter)"
}

How to remove 1 component in a string? Swift

I have this string "01:07:30" and I would like to remove the zero in "01" and keep everything else the same. My final string should look like this
"1:07:30"
Is there a way to do so in Swift? Thank you so much!
Try the following. This will create a string, check to see if the first character is 0 if it is remove it. Otherwise do nothing.
var myString = "01:07:30"
if myString.first == "0" {
myString.remove(at: myString.startIndex)
}
print(myString) // 1:07:30
The final result is the string will now be 1:07:30 instead of 01:07:30.
If I'm best understanding your question, you want to replace the occurrences of "01" with "1" in your string, so you can use regex or the string functionality it self
simply:
let searchText = "01"
let replaceWithValue = "1"
let string = "01:07:08:00:01:01"
let newString = string.replacingOccurrences(of: searchText, with: replaceWithValue) // "1:07:08:00:1:1"
If you want to replace the fist occurrence only, simply follow this answer:
https://stackoverflow.com/a/33822186/3911553
If you just want to deal with string here is one of many solution:
var myString = "01:07:30"
let list = myString.components(separatedBy: ":")
var finalString = ""
for var obj in list{
if obj.first == "0" {
obj.removeFirst()
}
finalString += finalString.count == 0 ? "\(obj)" : ":\(obj)"
}
print(finalString)

Check if an element is present in 3D array Swift

I have an array which gets instantiated in viewDidLoad like var bookingsArray : [[String]] = []
I am adding elements to it in this way:
var configuration: [String] = []
configuration.append(textfieldFacility.text!)
configuration.append((pickSlotTF.text?.components(separatedBy: " ")[0])!)
configuration.append((pickSlotTF.text?.components(separatedBy: " ")[1])!)
bookingsArray.append(configuration as [String])
bookingsArray looks like :
[["A", "20-08-2017", "14:00"], ["B", "20-08-2017", "14:00"]]
While adding new elements to bookingsArray, I want to check if the new element is already present in the array. How do I do it in this case of multi-dimensional array?
First of all, if you want unique objects use a Set.
If this is not possible I highly recommend to use a custom struct which can conform to Equatable rather than a nested array , for example
struct Booking : Equatable {
let facilty : String
let date : String
let time : String
static func ==(lhs : Booking, rhs : Booking) -> Bool {
return lhs.facilty == rhs.facilty && lhs.date == rhs.date && lhs.time == rhs.time
}
}
Then declare the array as
var bookingsArray = [Booking]()
and create an object with
let dateArray = pickSlotTF.text!.components(separatedBy: " ")
let configuration = Booking(facility: textfieldFacility.text!,
date: dateArray[0],
time = dateArray[1])
bookingsArray.append(configuration)
The huge benefit is that you can easily check
if bookingsArray.contains(item)
You can simply search for it with contains().
var configuration: [String] = []
configuration.append(textfieldFacility.text!)
configuration.append((pickSlotTF.text?.components(separatedBy: " ")[0])!)
configuration.append((pickSlotTF.text?.components(separatedBy: " ")[1])!)
if !bookingsArray.contains(where: {$0 == configuration}) {
bookingsArray.append(configuration)
}

Splitting a Swift String using a multi-Character String in Swift 2

I understand that I can fallback to the NSString function componentsSeparatedByString, and so perhaps this is a nitpick, but one of the things I like about Swift is that it is designed around brevity and short syntax.
I was really hoping I could just: var parts = myString.characters.split("${") but that function only works for a single Character, not a two Character string. I even tried var parts = myString.characters.split { $0 == "${" } but that is expecting a single Character as the delimiter and not a full String. :(
Is there an api function that I'm missing or do I need to stick with the the old NSString bridged functions?
Here's a rather simple-minded approach that makes it possible to use Swift split on a single character:
extension String {
mutating func replace(target:String, with:String) {
while let r = self.rangeOfString(target) {
self.replaceRange(r, with: with)
}
}
func split(separator:String) -> Array<String> {
var s = self
s.replace(separator, with:"☞") // arbitrary improbable character :)
return s.characters.split("☞").map{String($0)}
}
}
var s = "the${cat${sat${on${the${mat"
let arr = s.split("${")
However, rangeOfString is actually a Foundation method on NSString; if you don't import Foundation (or UIKit), that code won't compile. So in reality it's no improvement over just calling componentsSeparatedByString. I don't actually understand your objection to it in the first place; Swift has holes exactly because it expects Foundation to be backing it up and filling those holes.
'pure' Swift's solution where import Foundation is NOT required and arbitrary improbable character doesn't exists
let str = "t{he${cat${sat${on${the${mat"
let splitBy = "${"
extension String {
func split(splitBy: String)->[String] {
if self.isEmpty { return [] }
var arr:[String] = []
var tmp = self
var tmp1 = ""
var i = self.startIndex
let e = self.endIndex
let c = splitBy.characters.count
while i < e {
let tag = tmp.hasPrefix(splitBy)
if !tag {
tmp1.append(tmp.removeAtIndex(tmp.startIndex))
i = i.successor()
} else {
tmp.removeRange(Range(start: tmp.startIndex, end: tmp.startIndex.advancedBy(c)))
i = i.advancedBy(c)
arr.append(tmp1)
tmp1 = ""
}
}
arr.append(tmp1)
return arr.filter{ !$0.isEmpty }
}
}
let arr = str.split(splitBy) // ["t{he", "cat", "sat", "on", "the", "mat"]
If you have Foundation imported, you can use the components(separatedBy:) method to accomplish that.
let str = "Foo, Bar, Baz"
str.components(separatedBy: ", ")
Here are the docs.
(Tested on Ubuntu Linux)

Swift: Split String into sentences

I'm wondering how I can split a string containing several sentences into an array of the sentences.
I know about the split function but spliting by "." doesn't suite for all cases.
Is there something like mentioned in this answer
You can use NSLinguisticsTagger to identify SentenceTerminator tokens and then split into an array of strings from there.
I used this code and it worked great.
https://stackoverflow.com/a/57985302/10736184
let text = "My paragraph with weird punctuation like Nov. 17th."
var r = [Range<String.Index>]()
let t = text.linguisticTags(
in: text.startIndex..<text.endIndex,
scheme: NSLinguisticTagScheme.lexicalClass.rawValue,
tokenRanges: &r)
var result = [String]()
let ixs = t.enumerated().filter {
$0.1 == "SentenceTerminator"
}.map {r[$0.0].lowerBound}
var prev = text.startIndex
for ix in ixs {
let r = prev...ix
result.append(
text[r].trimmingCharacters(
in: NSCharacterSet.whitespaces))
prev = text.index(after: ix)
}
Where result will now be an array of sentence strings. Note that the sentence will have to be terminated with '?', '!', '.', etc to count. If you want to split on newlines as well, or other Lexical Classes, you can add
|| $0.1 == "ParagraphBreak"
after
$0.1 == "SentenceTerminator"
to do that.
If you are capable of using Apple's Foundation then solution could be quite straightforward.
import Foundation
var text = """
Let's split some text into sentences.
The text might include dates like Jan.13, 2020, words like S.A.E and numbers like 2.2 or $9,999.99 as well as emojis like πŸ‘¨β€πŸ‘©β€πŸ‘§β€πŸ‘¦! How do I split this?
"""
var sentences: [String] = []
text.enumerateSubstrings(in: text.startIndex..., options: [.localized, .bySentences]) { (tag, _, _, _) in
sentences.append(tag ?? "")
}
There are ways do it with pure Swift of course. Here is quick and dirty split:
let simpleText = """
This is a very simple text.
It doesn't include dates, abbreviations, and numbers, but it includes emojis like πŸ‘¨β€πŸ‘©β€πŸ‘§β€πŸ‘¦! How do I split this?
"""
let sentencesPureSwift = simpleText.split(omittingEmptySubsequences:true) { $0.isPunctuation && !Set("',").contains($0)}
It could be refined with reduce().
Take a look on this link :
How to create String split extension with regex in Swift?
it shows how to combine regex and componentsSeparatedByString.
Try this:-
var myString : NSString = β€œThis is a test”
var myWords: NSArray = myString.componentsSeparatedByString(β€œ β€œ)
//myWords is now: ["This", "is", "a", "test"]

Resources