Making an array with Strings and range of Integer merged - arrays

I would like to make a function that generates an array consists of Strings, and integers in range combined as a whole String. For example:
let fruit = "apple"
let numbers = Array(1...10)
let format = ".jpg"
->
["apple1.jpg", "apple2.jpg", "apple3.jpg", ..... "apple10.jpg"]
How can I combine a defined String with range of integers and put them in an array? Apologize for a newbie question. Much appreciated. <3

The simplest solution is you can directly use map on your range.
let array = (1...10).map({ "apple\($0).jpg" })
print(array) //["apple1.jpg", "apple2.jpg", "apple3.jpg", ..... "apple10.jpg"]

Use this:
func mergeStringAndInt(_ prefix: String, intArray: [Int], postfix: String) -> [String] {
return intArray.map {String(format: "%#%d%#", prefix, $0, postfix )}
}

You can do the like -
func resultArray() -> NSMutableArray {
var your_Array = NSMutableArray()
for item in numbers {
let combinedStr = "\(fruit)\(item).\(format)"
your_Array.add(combinedStr)
}
return your_Array
}

Related

Using returned value (array of Strings) in another Swift file

Apologize for a complete newbie question. This was the original array of Strings I wrote:
let fruit = ["apple1.jpg", "apple2.jpg", "apple3.jpg", ..... "apple10.jpg"]
First, I made a function in a separate Swift file (attached to the project) to replace above array, as the array's content might be changed based on several input factors later:
class Fruits {
let fruit = "apple"
func fruitName() -> [String] {
let arrayA = (1...10).map({ "\(fruit)\($0).jpg" })
return arrayA
}
}
}
This is everything written on Fruits.swift file. And then, back to original file, I wanted to replace the original let fruit = ["", "", ...] to something like let fruit = Fruits.fruitName() - by loading the returned arrayA. But it was a bit confusing to understand how to use returned String Array values in a different file, inside of a different Class bracket. I tried something like let fruits = Fruits(), let fruit = fruits.fruitName(), etc but it doesn't seem to successfully replace the original array code. I still need to create the constant let fruit = part. Is there any way to load the returned value in a separate file? Much appreciated. <3
If you want a property of a class to be directly accessible from anywhere in your code, you can make it static:
class Fruits {
static let fruit = "apple"
static func fruitName() -> [String] {
let arrayA = (1...10).map({ "\(fruit)\($0).jpg" })
return arrayA
}
}
// usage:
let fruits = Fruits.fruitName()
Depending on your specific situation, you could even not have a class and have a global function that takes the fruit as a parameter:
func fruitNames(fruit: String) -> [String] {
let arrayA = (1...10).map({ "\(fruit)\($0).jpg" })
return arrayA
}
// usage:
let fruits = fruitNames(fruit: "apple")

Swift 4 array issue in changing text colour

I have a string and I want to change colors of two words in that string. So, I created a function
func setup()
{
let main_string = "By continuing you agree to our Term of use and Privacy Policy "
var string_to_color = ["By continuing you agree to our","and"]
for i in 0..<2
{
let range = (main_string as NSString).range(of: string_to_color[i])
let attributedString = NSMutableAttributedString.init(string:main_string)
attributedString.addAttribute(NSAttributedStringKey.foregroundColor, value: UIColor.black , range: range)
privacyL.attributedText = attributedString
}
But, it only changes the colour for the second word and not for the first one.
Can anyone help?
let main_string = "By continuing you agree to our Term of use and Privacy Policy "
var string_to_color = ["By continuing you agree to our","and"]
for i in 0..<2
{
let range = (main_string as NSString).range(of: string_to_color[i])
let attributedString = NSMutableAttributedString.init(string:main_string)
attributedString.addAttribute(NSAttributedStringKey.foregroundColor, value: UIColor.black , range: range)
privacyL.attributedText = attributedString
}
You are overriding each time privacyL.attributedText, so you'll get only the "result" of last iteration.
Instead, do:
let attributedString = NSMutableAttributedString.init(string:main_string)
for i in 0..<2
{
let range = (main_string as NSString).range(of: string_to_color[i])
attributedString.addAttribute(NSAttributedStringKey.foregroundColor, value: UIColor.black , range: range)
}
privacyL.attributedText = attributedString
Now, next issues:
Don't do a loop for i in 0..<2, instead use at least the count of string_to_color (or a for each loop). If tomorrow you add a string in it or remove one, you'll encounter an issue.
Also range(of:) will return the first occurence found, so if you have:
let main_string = "and and"
var string_to_color = ["something", "and"]
only the first "and" will be colored.
You have then to iterate or use a NSRegularExpression.
Here is a related question: Color all occurrences of string in swift
Just want to add to Larme's answer. You can create extension of String, which will be responsible for string coloring
extension String {
func colored(_ strings: [String], with color: UIColor) -> NSAttributedString {
let attributedString: NSMutableAttributedString = NSMutableAttributedString(string: self)
for string in strings {
let range = (self as NSString).range(of: string)
attributedString.addAttribute(NSAttributedStringKey.foregroundColor, value: color , range: range)
}
return attributedString
}
}
And now you can use it anywhere in your code, like this:
let main_string = "By continuing you agree to our Term of use and Privacy Policy "
let string_to_color = ["By continuing you agree to our","and"]
privacyL.attributedText = main_string.colored(string_to_color, with: UIColor.red)

add multiple objects to swift array in for loop

for tempExportData in exportDataArray {
let tmpRegNO:NSString = (tempExportData as AnyObject).object(forKey: kRegisteredNo) as! NSString
print("tmpRegNO is",tmpRegNO)
var tmpNoArray:Array = [String]()
tmpNoArray.append(tmpRegNO as String)
print("Count is",tmpNoArray.count)
print("ARRAY is",tmpNoArray)
}
I am trying to add string value i.e tmpRegNO to the Array tmpNoArray.
In this I can able to add only one value to the array at a time.
How to add the next value to that array when it is looping for second time.
As already mentioned you have to declare the array before entering the loop.
Your code is very objectivecish. This is a swiftier version. Don't annotate types the compiler can infer and use key subscription rather than ugly casting to AnyObject and objectForKey:.
var tmpNoArray = [String]()
for tempExportData in exportDataArray {
let tmpRegNO = tempExportData[kRegisteredNo] as! String
print("tmpRegNO is",tmpRegNO)
tmpNoArray.append(tmpRegNO)
print("Count is",tmpNoArray.count)
print("ARRAY is",tmpNoArray)
}
You can even write the whole expression in one line:
let tmpNoArray = exportDataArray.flatMap { $0[kRegisteredNo] as? String }
You need move the tempNoArray initialization outside of your for in loop, if not the your array will be initialized once for every item in your exportDataArray remaining only the las item as consequence
You need something like this
var tmpNoArray:Array = [String]()
for tempExportData in exportDataArray{
if let tmpRegNO = tempExportData[kRegisteredNo] as? String
{
print("tmpRegNO is",tmpRegNO)
tmpNoArray.append(tmpRegNO as String)
print("Count is",tmpNoArray.count)
print("ARRAY is",tmpNoArray)
}
}

How to return an subset of Array of characters?

I am trying to dynamically chop an array of letters but I can't seem to reconvert the result back into a [String]
let letters:String = "abcdefghijklmnopqrstuvwxyz"
let lettersarray = Array(letters.characters)
var targetNum = 14 // Show just the first 14 characters
var resultsArray = [String]()
let resultsSlice = lettersarray.dropLast(lettersarray.count - targetNum) // Returns an Array Slice instead of an Array
let newresultsArray = Array(resultsSlice) // Returns Array<_element> instead of [String]
How do I return a [String] ie ["a","b","c"... eg]
You need to map the Character array back to String
let resultsArray = lettersarray.dropLast(lettersarray.count - targetNum).map{String($0)}
alternatively (credits to Leo Dabus)
let letters = "abcdefghijklmnopqrstuvwxyz"
let targetNum = 14
let resultsArray = letters.characters.prefix(targetNum).map{String($0)}
No need for an array here. It's hard to understand what you're trying to do, but if you just want the first 14 characters of a string, use the prefix method:
let s = String("abcdefghijklmno".characters.prefix(14))
Assuming that you are getting a String and want an array of characters which is a slice of characters from that String, you could use Swift's Half-Open Range Operator found here.
let letters:String = "abcdefghijklmnopqrstuvwxyz"
let lettersArray = Array(letters.characters)
let targetNum = 2
let resultsArray = lettersArray[0..<targetNum]
This will give you an ArraySlice<Character>. If you want an Array<Character> you could do this:
let resultsArray:Array<Character> = Array(lettersArray[0..<targetNum]) // ["a","b"]

How to get an array with Name stored as a string in swift

I have a program in which I have to make an string array equal to another array. The second array needs to be found by its name,
So for example something like this :
let StoreString1 = ["", ""]
let StoreString2 = ["", ""]
let FinalString = GetStringWithName("StoreString" + Number)
in C# its GetComponent("ComponentName");
Thanks for all answers, and sorry for the confusing way I wrote the question, because I didn’t really know hot to put it into words XD.
What you are trying to do can be achieved by using Dictionaries in swift. It appears that you are not familiar with this topic, so will be of no use to just throw out some code, there are many tutorials about this regard.
Just for mentioning one, (that has even images explaining how it works) you can enter here
Happy Learning & Coding! ;-)
UPDATE:
Here's a playground testing the concept: (Feel free to adjust it to your needs)
var dictionary: [String : [ String ]] = ["" : []]
let storeString = "StoreString"
func addUpdateArray(strings: [String], index: Int) {
let locator = storeString + index.description
dictionary[locator] = strings
}
func getStringWitNameIndex(index:Int) -> [String]? {
return dictionary[ storeString + index.description]
}
func addToArray(index:Int, inout destiny: [String]) {
if let array = getStringWitNameIndex(index) {
destiny = destiny + array
}
}
addUpdateArray(["Hello", "World"], 1)
addUpdateArray(["Hello", "Cats"], 3)
var finalArray : [String] = []
addToArray(1,&finalArray)
addToArray(3,&finalArray)
finalArray
In this case, finalArray ends up having: ["Hello", "World", "Hello",
"Cats"]

Resources