I want to make a substring extension for string , I tried below 2 ways but unsuccessful:
extension String
{
func substringToFirstChar(of char: Character) -> String
{
let pos = self.range(of: String(char))
let subString = self[..<pos?.lowerBound]
return String(subString)
}
}
or
extension String
{
func substringToFirstChar(of char: Character) -> String
{
let pos = self.index(of: char)
let subString = self[..<pos]
return String(subString)
}
}
xcode prompt error: Generic parameter 'Self' could not be inferred at the "let subString = self[.." line.
How to do that ?
range(of / index(of returns an optional. You have to unwrap the optional in the range expression
extension String
{
func substringToFirstChar(of char: Character) -> String?
{
guard let pos = self.range(of: String(char))?.lowerBound else { return nil }
// or guard let pos = self.index(of: char) else { return nil }
let subString = self[..<pos]
return String(subString)
}
}
alternatively – to avoid the optional – return the unchanged string if there is no match
extension String
{
func substringToFirstChar(of char: Character) -> String
{
guard let pos = self.range(of: String(char))?.lowerBound else { return self }
// or guard let pos = self.index(of: char) else { return self }
let subString = self[..<pos]
return String(subString)
}
}
Related
I am trying to implement my own web browser history for WKWebView on iOS, but I can't implement this functionality completely, and each time I obtain trouble.
I can create a history where the user did be and then moving forward and backward inside history.
But I have next trouble, and I think it an only one of many problems on my way.
When I have a history with for example 10 elements, and then I am moving back to element number 5 and then go don't forward but try to open the new link I can't remove element 6-10 and put the new link.
I think my problem that I can't fully understand how history work inside all browsers under the hood, this is not a hard task but I am confused inside this algorithm.
My main data structure for holding history
Help me understand how to work this algorithm inside browsers or maybe exist a good theory about it?
I have solved this problem and realize the full algorithm well, the completed project available here: https://github.com/IhorYachmenov/Custom-browser-history-for-WKWebView.
Algorithm:
struct PlayerHistory {
static var shared = PlayerHistory()
var historyExist: Bool = false
var historyCurrentPosition: Int = 0
var historyLastPositionBeforeUpdatingHistory: Int!
var userHistoryKey: String!
var backPressed: Bool!
var forwardPressed: Bool!
var urlOfPlayer: String!
// Function only for first loading inside <viewDidLoad or another method from app LifeCycle>.
mutating func getUrlForFirstLoading(initURL: String, key: String) -> String {
urlOfPlayer = initURL
guard HistoryStorage.shared.getHistoryFromUserDefaults() != nil else {
updateFirstElement(key: key, url: initURL)
return initURL
}
guard HistoryStorage.shared.getHistoryFromUserDefaults()![key] != nil else {
return initURL
}
let position = HistoryStorage.shared.getHistoryFromUserDefaults()![key]!.count - 1
historyExist = true
historyCurrentPosition = position
userHistoryKey = key
let initUrlFromHistoryStorage = HistoryStorage.shared.getHistoryFromUserDefaults()![key]!.last!.url
return initUrlFromHistoryStorage
}
// Create new or update exist history, use this method indsede <decidePolicyForNavigation>.
mutating func updatePlayerHistory(backlisk: [String], key: String) {
var history = [WebViewHistory]()
for i in backlisk {
history.append(WebViewHistory(i))
}
if (historyExist == true) {
// If old history exist need compound both and then to save.
let oldHistory = HistoryStorage.shared.getHistoryFromUserDefaults()![key]
let oldAndNewHostoryTogether = oldHistory! + history
var keyValuePair = Dictionary<String, [WebViewHistory]>()
keyValuePair.updateValue(oldAndNewHostoryTogether, forKey: key)
HistoryStorage.shared.removeHistory()
HistoryStorage.shared.saveHistory(keyValuePair)
setCurrentPosition(url: backlisk.last!, key: key)
} else {
var keyValuePair = Dictionary<String, [WebViewHistory]>()
keyValuePair.updateValue(history, forKey: key)
historyExist = true
HistoryStorage.shared.removeHistory()
HistoryStorage.shared.saveHistory(keyValuePair)
setCurrentPosition(url: backlisk.last!, key: key)
}
}
// Before using this method check if result don't equals nil. Use this method for navigation beetween history
func moveThroughHistory(key: String, direction: Bool) -> String? {
guard historyExist != false else {
return nil
}
let history = HistoryStorage.shared.getHistoryFromUserDefaults()![key]!
if (direction == true) {
let index = historyCurrentPosition + 1
guard index != history.count else { return nil }
return history[index].url
} else {
let index = historyCurrentPosition - 1
guard index > 0 else { return history[0].url }
return history[index].url
}
}
// Method <setCurrentPosition> each time set position at history
mutating func setCurrentPosition(url: String, key: String) {
guard HistoryStorage.shared.getHistoryFromUserDefaults() != nil else { return }
guard HistoryStorage.shared.getHistoryFromUserDefaults()![key] != nil else { return }
let history = HistoryStorage.shared.getHistoryFromUserDefaults()![key]
let index = history?.firstIndex(of: WebViewHistory(url))
guard index != nil else {
historyCurrentPosition = 0
return
}
historyCurrentPosition = index!
}
// <removeUnusedPeaceOfHistory> need use when user want open new page staying inside the middle of history
mutating func removeUnusedPeaceOfHistory(key: String) {
guard HistoryStorage.shared.getHistoryFromUserDefaults() != nil else {
return
}
guard HistoryStorage.shared.getHistoryFromUserDefaults()![key] != nil else {
return
}
var history = HistoryStorage.shared.getHistoryFromUserDefaults()![key]!
let startIndex = historyCurrentPosition + 1
let endIndex = history.endIndex - 1
let countOfAllElements = history.count
guard startIndex != countOfAllElements else { return }
let range = startIndex...endIndex
history.removeSubrange(range)
var keyValuePair = Dictionary<String, [WebViewHistory]>()
keyValuePair.updateValue(history, forKey: key)
HistoryStorage.shared.removeHistory()
HistoryStorage.shared.saveHistory(keyValuePair)
}
// Use <updateFirstElement> inside <getUrlForFirstLoading> if history doesn't exist
private mutating func updateFirstElement(key: String, url: String) {
var history = [WebViewHistory]()
history.insert(WebViewHistory(url), at: 0)
var keyValuePair = Dictionary<String, [WebViewHistory]>()
keyValuePair.updateValue(history, forKey: key)
HistoryStorage.shared.saveHistory(keyValuePair)
historyExist = true
historyCurrentPosition = 0
}
// Use <webViewWillBeClosedSaveHistory> when WKWebView should be closed, if the user moves through history new position will be saved.
mutating func webViewWillBeClosedSaveHistory(key: String) {
let history = HistoryStorage.shared.getHistoryFromUserDefaults()![key]!
let currentPosition = historyCurrentPosition + 1
guard currentPosition != history.count else { return }
removeUnusedPeaceOfHistory(key: key)
}
}
func showNumbers(){
if let inputString = numberInput.text {
let input = Int(inputString)
let nums = input?.formattedWithSeparator
let group = Int(round(groupslider.value))
let priceEach = Int(round(Double((nums)!/group*100))/100)
perperson.text = String(priceEach)
}
}
}
extension Formatter {
static let withSeparator: NumberFormatter = {
let formatter = NumberFormatter()
formatter.groupingSeparator = " "
formatter.numberStyle = .decimal
return formatter
}()
}
extension BinaryInteger {
var formattedWithSeparator: String {
return Formatter.withSeparator.string(for: self) ?? ""
}
}
I have two places that I want to make it like 1,000,000
input String and perperson.text
what should I use? NSNumberForatter?
I want to use thousandSeparator or groupSeparator.
I get " Binary operator '/' cannot be applied to operands of type 'String' and 'Int' " this error message.
I have a string
var str = "1 2 3 4"
and I want to convert it into [Int]. It can be done as follow
let intArray = str.characters.split {$0 == " "}.map(String.init).map { Int($0)!}
Now what if my string is
var invalid = " 1 a 4"
Then, the program will crash with
fatal error: unexpectedly found nil while unwrapping an Optional value
I need to be able to check number and throw number format error in map.
You can use throws, try - throw, do - try - catch and guard (if) for that. Here is the code
var invalid = " 1 a 4"
let intArray: [Int]
do {
intArray = try getIntArray(invalid, delimiter: " ")
}catch let error as NSError {
print(error)
intArray = []
}
func getIntArray(input:String, delimiter:Character ) throws -> [Int] {
let strArray = input.characters.split {$0 == delimiter}.map(String.init)
let intArray = try strArray.map {
(int:String)->Int in
guard Int(int) != nil else {
throw NSError.init(domain: " \(int) is not digit", code: -99, userInfo: nil)
}
return Int(int)!
}
return intArray
}
In getIntArray function, We first convert the input string to string array.
Then when we are converting string array to int array, we are expanding the map closure function parameter to include number format checking and throwing error using "guard".
"guard" can be replaced with "if" too if it is not available
if Int(int) == nil {
throw NSError.init(domain: " \(int) is not digit", code: -99, userInfo: nil)
}
Rather than throwing NSError types, you can create your own Swift native enum conforming to ErrorType where your enumeration contains the error case you would like to explicitly handle. E.g.
enum MyErrors : ErrorType {
case NumberFormatError(String)
}
/* throwing function attempting to initialize an
integer given a string (if failure: throw error) */
func strToInt(str: String) throws -> Int {
guard let myInt = Int(str) else { throw MyErrors.NumberFormatError(str) }
return myInt
}
Example usage within a do-try-catch construct:
func strAsIntArr(str: String) -> [Int]? {
var intArr: [Int] = []
do {
intArr = try str.characters.split {$0 == " "}
.map(String.init)
.map { try strToInt($0) }
} catch MyErrors.NumberFormatError(let faultyString) {
print("Format error: '\(faultyString)' is not number convertible.")
// naturally you could rethrow here to propagate the error
} catch {
print("Unknown error.")
}
return intArr
}
/* successful example */
let myStringA = "1 2 3 4"
let intArrA = strAsIntArr(myStringA)
/*[1, 2, 3, 4] */
/* error throwing example */
let myStringB = "1 b 3 4"
let intArrB = strAsIntArr(myStringB)
/* [], Format error: 'b' is not number convertible. */
Until Swift 2 I used this extension to remove multiple whitespaces:
func condenseWhitespace() -> String {
let components = self.componentsSeparatedByCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet()).filter({!Swift.isEmpty($0)})
return " ".join(components)
}
but with Swift 2 now I get the error
Cannot invoke 'isEmpty' with an argument list of type '(String)'
How could I now remove multiple spaces with Swift 2?
Thnx!
In Swift 2, join has become joinWithSeparator and you call it on the array.
In filter, isEmpty should be called on the current iteration item $0.
To replace whitespaces and newline characters with unique space characters as in your question:
extension String {
func condenseWhitespace() -> String {
let components = self.componentsSeparatedByCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet())
return components.filter { !$0.isEmpty }.joinWithSeparator(" ")
}
}
let result = "Hello World.\nHello!".condenseWhitespace() // "Hello World. Hello!"
Because your function does not take any parameter you could make it a property instead:
extension String {
var condensedWhitespace: String {
let components = self.componentsSeparatedByCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet())
return components.filter { !$0.isEmpty }.joinWithSeparator(" ")
}
}
let result = "Hello World.\nHello!".condensedWhitespace // "Hello World. Hello!"
In Swift 3 there's even more changes.
Function:
extension String {
func condenseWhitespace() -> String {
let components = self.components(separatedBy: NSCharacterSet.whitespacesAndNewlines)
return components.filter { !$0.isEmpty }.joined(separator: " ")
}
}
let result = "Hello World.\nHello!".condenseWhitespace()
Property:
extension String {
var condensedWhitespace: String {
let components = self.components(separatedBy: NSCharacterSet.whitespacesAndNewlines)
return components.filter { !$0.isEmpty }.joined(separator: " ")
}
}
let result = "Hello World.\nHello!".condensedWhitespace
In Swift 4.2 NSCharacterSet is now CharacterSet, and you can omit and use dot syntax:
extension String {
func condenseWhitespace() -> String {
let components = self.components(separatedBy: .whitespacesAndNewlines)
return components.filter { !$0.isEmpty }.joined(separator: " ")
}
}
let result = "Hello World.\nHello!".condenseWhitespace() // "Hello World. Hello!"
Split string to array and then join again in not memory efficient. Its Takes lot of memory. The best way in this case is to scan the given string and perform operations on that. Regular Expression is the advance way to scan a text. For the above conclusion the the solution is given below:
Swift 4.x
extension String {
func removeExtraSpaces() -> String {
return self.replacingOccurrences(of: "[\\s\n]+", with: " ", options: .regularExpression, range: nil)
}
}
Usages
let startingString = "hello world! \n\n I am here!"
let processedString = startingString.removeExtraSpaces()
print(processedString)
Output:
processedString => "hello world! I am here!"
You can Do more according to your own requirements but thing I am pointing out here is to use regular expressions with string rather then create arrays which will consume lot of memory.
Cleanest version. Documented, memory efficient, extremely easy to use.
extension String {
/// Returns a condensed string, with no extra whitespaces and no new lines.
var condensed: String {
return replacingOccurrences(of: "[\\s\n]+", with: " ", options: .regularExpression, range: nil)
}
/// Returns a condensed string, with no whitespaces at all and no new lines.
var extraCondensed: String {
return replacingOccurrences(of: "[\\s\n]+", with: "", options: .regularExpression, range: nil)
}
}
Usage:
let a = " Hello\n I am a string ".condensed
let b = " Hello\n I am a string ".extraCondensed
Output:
a: "Hello I am a string"
b: "HelloIamastring"
SWIFT 3: Cleaner version
extension String {
var condensedWhitespace: String {
let components = self.components(separatedBy: .whitespacesAndNewlines)
return components.filter { !$0.isEmpty }.joined(separator: " ")
}
}
Here is mine: How it's actually worked.
extension String {
func removeExtraSpaces() -> String {
var data = ""
var numberOfSpace = 0
let items = self.getComponents(separatedBy: " ")
for item in items{
if item == " "{
numberOfSpace = numberOfSpace + 1
}else{
numberOfSpace = 0
}
if numberOfSpace == 1 || numberOfSpace == 0 {
data = data + item
//data.append(item)
}
}
return data
}
}
Usages
var message = "What is the purpose of life?"
message = message.removeExtraSpaces()
print(message)
Output:
What is the purpose of life?
var str = "Hello World.\nHello!"
if let regex = try? NSRegularExpression(pattern: "\\s+", options:NSRegularExpression.Options.caseInsensitive)
{
str = regex.stringByReplacingMatches(in: str, options: [], range: NSMakeRange(0, str.count), withTemplate: " ")
}
This function takes in an Int like 324543 and returns a String like "$3245.43"
My attempt is below, but Swift 2 does not like atIndex: 0
How would I go about inserting characters into a string instead?
func stylizeCents (cent: Int) -> String {
var styledCents = String(cent)
let dollarSign : Character = "$"
let dot : Character = "."
let count = styledCents.characters.count
styledCents.insert(dollarSign, atIndex: 0) // error
styledCents.insert(dot, atIndex: count-1) // error
}
This appears to have already been solved in this answer.
Swift 2.0
You can use a string extension:
extension String {
func insert(string:String,ind:Int) -> String {
return String(self.characters.prefix(ind)) + string + String(self.characters.suffix(self.characters.count-ind))
}
}
used like:
var url = "http://www.website.com"
url = url.insert("s", ind: 4) // outputs https://www.website.com