Expeceted Declaration when using for loop [duplicate] - swift

This question already has an answer here:
Expected Declaration Error using Swift
(1 answer)
Closed 5 years ago.
Im just trying to use a for loop to run through some code, but I get an Expected declaration error.
var index = 0
for( i in 0..< array.count) {
let commonPrefix = array[i].commonPrefixWithString(array[index], options: .CaseInsensitiveSearch)
if (countElements(commonPrefix) == 0 ) {
let string = array[index].uppercased();
let firstCharacter = string[string.startIndex]
let title = "\(firstCharacter)"
let newSection = (index: index, length: i - index, title: title)
sections.append(newSection)
index = i
}
}
Help

That's not how you write a for loop in Swift. What you want is this
for i in 0..<array.count {
// the loop inner body
}

Related

How can I remove character in specific range [duplicate]

This question already has an answer here:
Understanding the removeRange(_:) documentation
(1 answer)
Closed 2 years ago.
how can i remove character from string with rang. for example «banana» i want to remove only a from index (1..<3), i don’t want to remove the first and last character if they where «a»
i want from banana to bnna only removed the two midle.
the only thing i can do now is to remove the all “a”.
var charr = "a"
var somfruit = "banana"
var newString = ""
for i in somfruit{
if charr.contains(i) {
continue
}
newString.append(i)
}
print(newString)
In SWIFT 5 try:
var charr = "a"
var somfruit = "banana"
var newString = ""
let lower = somfruit.firstIndex(of: charr) + 1
let upper = somfruit.lastIndex(of: charr) - 1
newString = somfruit.replacingOccurrences(of: charr, with: '', option: nil, range: Range(lower, upper)
print(newString)
This is simplified. firstIndex and lastIndex returns Int? so you have to check they exist and they are not equals.

How to masking textfield in Swift 4? [duplicate]

This question already has answers here:
How to masking the last number in Swift?
(2 answers)
Closed 3 years ago.
I want masking email in textfield.text, but I only get the value in the middle. I want to get the value from the middle to # gmail.com like example below.
ex:
let var = 12345678#gmail.com
output = ****5678#gmail.com
let var = 123456789#gmail.com
output = ****56789#gmail.com
let email = "123456789#gmail.com"
let components = email.components(separatedBy: "#")
let result = hideMidChars(components.first!) + "#" + components.last!
print(result)
output I get: ****5****#gmail.com
my expectations: ****56789#gmail.com
try extending the string protocol and declare a variable which returns an .init(repeating: ,count):
extension StringProtocol {
var masked: String {
return String(repeating: "•", count: Swift.max(0, count - count/2)) + suffix(count/2)
}
}
usage as follows:
let email = "123456789#gmail.com"
print(email.masked) //"••••••••••gmail.com"
if you want a part of the email showing just manipulate the suffix(count - 3) as follows:
return String(repeating: "•", count: Swift.max(0, count - count/2)) + suffix(count/2)
func hide(email: String) -> String {
let parts = email.split(separator: "#")
if parts.count < 2 {
return email
}
let name = parts[0]
let appendix = parts[1]
let lenght = name.count
if lenght == 1 {
return "*#\(appendix)"
}
let semiLenght = lenght / 2
var suffixSemiLenght = semiLenght
if (lenght % 2 == 1) {
suffixSemiLenght += 1
}
let prefix = String(repeating: "*", count: semiLenght)
let lastPart = String(name.suffix(suffixSemiLenght))
let result = "\(prefix)\(lastPart)#\(appendix)"
return result
}
let email = "123456789#gmail.com"
let result = hide(email: email)
print(result)

How do you split a string at every n-th character in Swift? [duplicate]

This question already has answers here:
How to split a string into substrings of equal length
(13 answers)
Closed 4 years ago.
Like the question says, if I have:
XQQ230IJFEKJLDSAIOUOIDSAUIFOPDSFE28
How can I split this string at every 8th character to get:
XQQ230IJ FEKJLDSA IOUOIDSA UIFOPDSA
Implement this function
extension String {
func inserting(separator: String, every n: Int) -> String {
var result: String = ""
let characters = Array(self.characters)
stride(from: 0, to: characters.count, by: n).forEach {
result += String(characters[$0..<min($0+n, characters.count)])
if $0+n < characters.count {
result += separator
}
}
return result
}
}
call it this way,
let str = "XQQ230IJFEKJLDSAIOUOIDSAUIFOPDSFE28"
let final = str.inserting(separator: " ", every: 8)
print(final)
Output will be like this,
XQQ230IJ FEKJLDSA IOUOIDSA UIFOPDSF E28
This will be generic solution if you want to add any character instead of space, it will work.

How do a i+=2 for-loop in Swift? [duplicate]

This question already has answers here:
Swift 3 for loop with increment
(5 answers)
Closed 5 years ago.
for example, a Java for-loop:
for(int i=0; i<5; i+=1){
//
}
convert to Swift
for index in 0..<5 {
}
but what if i+=2?
I'm new to Swift.. Maybe it's a stupid question, but will be appreciate if you answer it, thx! :-)
Check this
for index in stride(from: 0, to: 5, by: 2){
print(index)
}
You can use this way as well.
var first = 0
var last = 10
var add = 2
for i in sequence(first: first, next: { $0 + add })
.prefix(while: { $0 <= last }) {
print(i)
}
Output will be: 0,2,4,6,8,10
In case if your for loop was doing something more complex than adding constant value to index each iteration you may use something like that:
Assuming you have this for loop:
for(index = initial; condition(index); mutation(index)){
//
}
Where
initial — initial value constant of type T
condition — function (T) -> Bool, that checks if loop should end
mutation — function (T) -> T, that changes index value each iteration
Then it will be:
for index in sequence(first: initial, next: { current in
let next = mutation(current)
return condition(next) ? next : nil
}) {
//
}

Calculate count of years

I have a String data that stores date. Example:
let dates = ["1-Jan-2015", "1-Feb-2015", "20-Mar-2014", "15-Apr-2014", "12-May-2013", "23-Jun-2012"]
I need to do a count of how many times did that year occurs, and then store it. So what I require would be something like that
let years = ["2015" : 2, "2014" : 2, "2013" : 1, "2012" : 1]
I would like to avoid hard coding it for future growth. Meaning say if I have Year 2020, I cannot be hard coding all the years to store these values.
So the problem here is I've got no idea how should I do this on the overview. In addition, how do I convert the String format to date?
let dates = ["1-Jan-2015", "1-Feb-2015", "20-Mar-2014", "15-Apr-2014", "12-May-2013", "23-Jun-2012"]
// map the last 4 characters of your string
let years = dates.map{String($0.characters.suffix(4))}
// create a dictionary to store tue frequency
var frequencies:[String:Int] = [:]
// loop through the years
for year in years {
// increase it
frequencies[year] = (frequencies[year] ?? 0) + 1
}
let sortedFrequencies = frequencies.sort{ $0.0 < $1.0 }
print(sortedFrequencies) // [("2012", 1), ("2013", 1), ("2014", 2), ("2015", 2)]\n"
I have created the following solution. Use the following function and it will give you the following result in the screenshot
/// This function will return the array as per your requirement
func getyears(dates: NSArray) -> NSArray
{
var year = [String]()
let newdates = dates
var countvalue = 0
for i in dates {
let x = i.stringByReplacingOccurrencesOfString("-", withString: "")
let startIndex = x.endIndex.advancedBy(-4)
let lastFourDigitsOfdate = x.substringFromIndex(startIndex)
for xm in newdates
{
let xy = xm.stringByReplacingOccurrencesOfString("-", withString: "")
let startIndex1 = xy.endIndex.advancedBy(-4)
let lastFourDigitsOfdate1 = xy.substringFromIndex(startIndex1)
if lastFourDigitsOfdate == lastFourDigitsOfdate1
{
countvalue = countvalue + 1
}
}
year.append("\(lastFourDigitsOfdate) : \(countvalue)")
countvalue = 0
}
return getUniqArrayData(year)
}
// This function will be required to get an unque array
func getUniqArrayData<S: SequenceType, E: Hashable where E==S.Generator.Element>(source: S) -> [E] {
var seen: [E:Bool] = [:]
return source.filter { seen.updateValue(true, forKey: $0) == nil }
}
let dates = ["1-Jan-2015", "1-Feb-2015", "20-Mar-2014", "15-Apr-2014", "12-May-2013", "23-Jun-2012"]
//Calling the above function
getyears(dates)
Hope this will be helpful.