Join strings in a block - swift

I have a block that updates the view for each String. In its object class I pass it by:
func eachFeaturesSection(block: ((String?) -> Void)?) {
propertyFeatures.forEach { feature in
guard let feature = feature as? RealmString else {
return
}
let features = feature.stringValue
block?(features)
}
}
and I will get it in ViewController, by:
listing!.eachFeaturesSection({ (features) in
print(features)
self.facilities = features!
})
So it will print as:
Optional("String 1")
Optional("String 2")
and self.facilities will be set to latest value which is self.facilities = "String 2"
cell.features.text = features // it will print String 2
So, how can I achieve to join all strings together in one string such as self.facilities = "String 1, String 2". I used .jointString does not work. Thank you for any help.

Maybe you could add them to an array of String elements and then, when done, call joined on that array.
So something like this in your ViewController:
var featuresArray = [String]()
listing!.eachFeaturesSectionT({ (features) in
print(features)
featuresArray.append(features!)
})
//Swift 3 syntax
cell.features.text = featuresArray.joined(separator: ", ")
//Swift 2 syntax
cell.features.text = featuresArray.joinWithSeparator(", ")
Hope that helps you.

self.facilities = features! is doing nothing but keeps updating the value every iteration
Change the line self.facilities = features! to self.facilities += features! or self.facilities = self.facilities + ", " + features!

Here's how I'd do it (assuming your propertyFeatures is an array of RealmString):
Swift 3:
let string = (propertyFeatures.map { $0.stringValue }).joined(separator: ", ")
Swift 2:
let string = (propertyFeatures.map { $0.stringValue }).joinWithSeparator(", ")

Related

swift 3 loop error (taking variable and adding it by itself)

My code does not work right now. I am trying to take names and add it by itself in the loop but the complier is giving me a error message and the code is not being printed.
let names = [Double(2),3,8] as [Any]
let count = names.count
for i in 0..<count {
print((names[i]) + names[i])
}
Because Any doesn't have + operator.
This will give you the result you expected.
If you want to add 2 values and print the result, you need to cast Any to calculatable like Double
let names = [Double(2),3,8] as [Any]
let count = names.count
for i in 0..<count {
if let value = names[i] as? Double {
print(value + value)
}
}
The use of as [Any] makes no sense. You can't add two objects of type Any which is probably what your error is about.
Simply drop it and your code works.
let names = [Double(2),3,8]
let count = names.count
for i in 0..<count {
print(names[i] + names[i])
}
Output:
4.0
6.0
16.0
Better yet:
let names = [Double(2),3,8]
for num in names {
print(num + num)
}

Swift split string to array with exclusion

I write Swift application that parse log file.
log file string:
substr1 substr2 "substr 3" substr4
I need to get array: [substr1, substr2, substr 3, substr4]
But if I use something like:
print(stringLine.components(separatedBy: " "))
I got: [substr1, substr2, "substr, 3", substr4].
How to receive array: [substr1, substr2, substr 3, substr4]?
One of the possible solutions is to use map:
let testSting = "substr1 substr2 \"substr3\" substr4"
let mappedString = testString.components(separatedBy: " ").map({$0.replacingOccurrences(of: "\"", with: "")})
print(mappedString) //["substr1", "substr2", "substr3", "substr4"]
This case of the issue is required to use regular expression but this example is provided. So to solve problem in you're case it is possible to go in this way:
var testStingArray = testSting.replacingOccurrences(of: "\"", with: "").components(separatedBy: " ")
var arr = [String]()
var step = 0
while step < testStingArray.count {
var current = testStingArray[step]
var next = step + 1
if next < testStingArray.count {
if testStingArray[next].characters.count == 1 {
current += " " + testStingArray[next]
testStingArray.remove(at: next)
}
}
arr.append(current)
step += 1
}
print(arr)//["substr1", "substr2", "substr 3", "substr4"]
You'd better work with regular expression:
let pattern = "([^\\s\"]+|\"[^\"]+\")"
let regex = try! NSRegularExpression(pattern: pattern, options: [])
let line = "substr1 substr2 \"substr 3\" substr4"
let arr = regex.matches(in: line, options: [], range: NSRange(0..<line.utf16.count))
.map{(line as NSString).substring(with: $0.rangeAt(1)).trimmingCharacters(in: CharacterSet(charactersIn: "\""))}
print(arr) //->["substr1", "substr2", "substr 3", "substr4"]
Alternatively you could split the string based on a CharacterSet and then filter out the empty occurrences:
let stringLine = "substr1 substr2 \"substr3\" substr4"
let array = stringLine.components(separatedBy: CharacterSet(charactersIn: "\" ")).filter { !$0.isEmpty }
print (array)
Output: ["substr1", "substr2", "substr3", "substr4"]
But this will not work correctly if there is a " somewhere in one of the 'substrings', then that specific substring will also be split.
Or, simply iterate over the characters and maintain state about the quoted parts:
//: Playground - noun: a place where people can play
import UIKit
extension String {
func parse() -> [String] {
let delimiter = Character(" ")
let quote = Character("\"")
var tokens = [String]()
var pending = ""
var isQuoted = false
for character in self.characters {
if character == quote {
isQuoted = !isQuoted
}
else if character == delimiter && !isQuoted {
tokens.append(pending)
pending = ""
}
else {
pending.append(character)
}
}
// Add final token
if !pending.isEmpty {
tokens.append(pending)
}
return tokens
}
}
print ("substr1 substr2 \"substr 3\" substr4".parse()) // ["substr1", "substr2", "substr 3", "substr4"]
print ("\"substr 1\" substr2 \"substr 3\" substr4".parse()) // ["substr 1", "substr2", "substr 3", "substr4"]
print ("a b c d".parse()) // ["a", "b", "c", "d"]
Note: this code doesn't take into account that double quotes "" might be used to escape a single quote. But I don't know if that's a possibility in your case.
https://tburette.github.io/blog/2014/05/25/so-you-want-to-write-your-own-CSV-code/

Search multiple words in one string in swift

I have a long string in swift3 and want to check if it contains word1 and word2. It could also be more than 2 search words. I found out following solution:
var Text = "Hello Swift-world"
var TextArray = ["Hello", "world"]
var count = 0
for n in 0..<TextArray.count {
if (Text.contains(TextArray[n])) {
count += 1
}
}
if (count == TextArray.count) {
print ("success")
}
But this seems very complicated, is there not an easier way to solve this? (Xcode8 and swift3)
If you are looking for less code:
let text = "Hello Swift-world"
let wordList = ["Hello", "world"]
let success = !wordList.contains(where: { !text.contains($0) })
print(success)
It is also a little more efficient than your solution because
the contains method returns as soon as a "not contained" word
is found.
As of Swift 4 or later, you can use allSatisfy:
let success = wordList.allSatisfy(text.contains)
A more Swifty solution that will stop searching after it found a non-existent word:
var text = "Hello Swift-world"
var textArray = ["Hello", "world"]
let match = textArray.reduce(true) { !$0 ? false : (text.range(of: $1) != nil ) }
Another way to do it which stops after it found a non-match:
let match = textArray.first(where: { !text.contains($0) }) == nil
Another possibility is regular expressions:
// *'s are wildcards
let regexp = "(?=.*Hello*)(?=.*world*)"
if let range = Text.range(of:regexp, options: .regularExpression) {
print("this string contains Hello world")
} else {
print("this string doesn't have the words we want")
}

swift: how can I delete a specific character?

a string such as ! !! yuahl! ! , I want delete ! and , when I code like this
for index in InputName.characters.indices {
if String(InputName[index]) == "" || InputName.substringToIndex(index) == "!" {
InputName.removeAtIndex(index)
}
}
have this error " fatal error: subscript: subRange extends past String end ", how should I do? THX :D
Swift 5+
let myString = "aaaaaaaabbbb"
let replaced = myString.replacingOccurrences(of: "bbbb", with: "") // "aaaaaaaa"
If you need to remove characters only on both ends, you can use stringByTrimmingCharactersInSet(_:)
let delCharSet = NSCharacterSet(charactersInString: "! ")
let s1 = "! aString! !"
let s1Del = s1.stringByTrimmingCharactersInSet(delCharSet)
print(s1Del) //->aString
let s2 = "! anotherString !! aString! !"
let s2Del = s2.stringByTrimmingCharactersInSet(delCharSet)
print(s2Del) //->anotherString !! aString
If you need to remove characters also in the middle, "reconstruct from the filtered output" would be a little bit more efficient than repeating single character removal.
var tempUSView = String.UnicodeScalarView()
tempUSView.appendContentsOf(s2.unicodeScalars.lazy.filter{!delCharSet.longCharacterIsMember($0.value)})
let s2DelAll = String(tempUSView)
print(s2DelAll) //->anotherStringaString
If you don't mind generating many intermediate Strings and Arrays, this single liner can generate the expected output:
let s2DelAll2 = s2.componentsSeparatedByCharactersInSet(delCharSet).joinWithSeparator("")
print(s2DelAll2) //->anotherStringaString
I find that the filter method is a good way to go for this sort of thing:
let unfiltered = "! !! yuahl! !"
// Array of Characters to remove
let removal: [Character] = ["!"," "]
// turn the string into an Array
let unfilteredCharacters = unfiltered.characters
// return an Array without the removal Characters
let filteredCharacters = unfilteredCharacters.filter { !removal.contains($0) }
// build a String with the filtered Array
let filtered = String(filteredCharacters)
print(filtered) // => "yeah"
// combined to a single line
print(String(unfiltered.characters.filter { !removal.contains($0) })) // => "yuahl"
Swift 3
In Swift 3, the syntax is a bit nicer. As a result of the Great Swiftification of the old APIs, the factory method is now called trimmingCharacters(in:). Also, you can construct the CharacterSet as a Set of single-character Strings:
let string = "! !! yuahl! !"
string.trimmingCharacters(in: [" ", "!"]) // "yuahl"
If you have characters in the middle of the string you would like to remove as well, you can use components(separatedBy:).joined():
let string = "! !! yu !ahl! !"
string.components(separatedBy: ["!", " "]).joined() // "yuahl"
H/T #OOPer for the Swift 2 version
func trimLast(character chars: Set<Character>) -> String {
let str: String = String(self.reversed())
guard let index = str.index(where: {!chars.contains($0)}) else {
return self
}
return String((str[index..<str.endIndex]).reversed())
}
Note:
By adding this function in String extension, you can delete the specific character of string at last.
for index in InputName.characters.indices.reversed() {
if String(InputName[index]) == "" || InputName.substringToIndex(index) == "!" {
InputName.removeAtIndex(index)
}
}
Also you can add such very helpful extension :
import Foundation
extension String{
func exclude(find:String) -> String {
return stringByReplacingOccurrencesOfString(find, withString: "", options: .CaseInsensitiveSearch, range: nil)
}
func replaceAll(find:String, with:String) -> String {
return stringByReplacingOccurrencesOfString(find, withString: with, options: .CaseInsensitiveSearch, range: nil)
}
}
you can use this:
for example if you want to remove "%" the percent from 10%
if let i = text.firstIndex(of: "%") {
text.remove(at: i) //10
}

How to capitalize the first character of sentence using Swift

I have a String description that holds my sentence and want to capitalize only the first letter. I tried different things but most of them give me exceptions and errors. I'm using Xcode 6.
Here is what I tried so far:
let cap = [description.substringToIndex(advance(0,1))] as String
description = cap.uppercaseString + description.substringFromIndex(1)
It gives me:
Type 'String.Index' does not conform to protocol 'IntegerLiteralConvertible'
I tried:
func capitalizedStringWithLocale(locale:0) -> String
But I haven't figured out how to make it work.
In Swift 2, you can do
String(text.characters.first!).capitalizedString + String(text.characters.dropFirst())
Another possibility in Swift 3:
extension String {
func capitalizeFirst() -> String {
let firstIndex = self.index(startIndex, offsetBy: 1)
return self.substring(to: firstIndex).capitalized + self.substring(from: firstIndex).lowercased()
}
}
For Swift 4:
Warnings from above Swift 3 code:
'substring(to:)' is deprecated: Please use String slicing subscript
with a 'partial range upto' operator.
'substring(from:)' is deprecated: Please use String slicing subscript with a 'partial range from' operator.
Swift 4 solution:
extension String {
var capitalizedFirst: String {
guard !isEmpty else {
return self
}
let capitalizedFirstLetter = charAt(i: 0).uppercased()
let secondIndex = index(after: startIndex)
let remainingString = self[secondIndex..<endIndex]
let capitalizedString = "\(capitalizedFirstLetter)\(remainingString)"
return capitalizedString
}
}
Swift 5.0
Answer 1:
extension String {
func capitalizingFirstLetter() -> String {
return prefix(1).capitalized + dropFirst()
}
mutating func capitalizeFirstLetter() {
self = self.capitalizingFirstLetter()
}
}
Answer 2:
extension String {
func capitalizeFirstLetter() -> String {
return self.prefix(1).capitalized + dropFirst()
}
}
Answer 3:
extension String {
var capitalizeFirstLetter:String {
return self.prefix(1).capitalized + dropFirst()
}
}
import Foundation
// A lowercase string
let description = "the quick brown fox jumps over the lazy dog."
// The start index is the first letter
let first = description.startIndex
// The rest of the string goes from the position after the first letter
// to the end.
let rest = advance(first,1)..<description.endIndex
// Glue these two ranges together, with the first uppercased, and you'll
// get the result you want. Note that I'm using description[first...first]
// to get the first letter because I want a String, not a Character, which
// is what you'd get with description[first].
let capitalised = description[first...first].uppercaseString + description[rest]
// Result: "The quick brown fox jumps over the lazy dog."
You may want to make sure there's at least one character in your sentence before you start, as otherwise you'll get a runtime error trying to advance the index beyond the end of the string.
Here is how to do it in Swift 4; just in case if it helps anybody:
extension String {
func captalizeFirstCharacter() -> String {
var result = self
let substr1 = String(self[startIndex]).uppercased()
result.replaceSubrange(...startIndex, with: substr1)
return result
}
}
It won't mutate the original String.
extension String {
var capitalizedFirstLetter:String {
let string = self
return string.replacingCharacters(in: startIndex...startIndex, with: String(self[startIndex]).capitalized)
}
}
Answer:
let newSentence = sentence.capitalizedFirstLetter
For one or each word in string, you can use String's .capitalized property.
print("foo".capitalized) //prints: Foo
print("foo foo foo".capitalized) //prints: Foo Foo Foo
Swift 4.2 version:
extension String {
var firstCharCapitalized: String {
switch count {
case 0:
return self
case 1:
return uppercased()
default:
return self[startIndex].uppercased() + self[index(after: startIndex)...]
}
}
}
Simplest soulution for Swift 4.0.
Add as a computed property extension:
extension String {
var firstCapitalized: String {
var components = self.components(separatedBy: " ")
guard let first = components.first else {
return self
}
components[0] = first.capitalized
return components.joined(separator: " ")
}
}
Usage:
"hello world".firstCapitalized