I created an array of words and I shuffled it.
I added a button and I want it to print one of the randomisers words in the array in a label. I know how to do that with integers but with stings it seems to be different. How can I do?
This is my code:
IBOutlet weak var label : UILabel!
IBAction getText(_ sender: Any) {
let words = textView.text.components.shuffled()
print (words)
}
I thought I had to add in my button something like
label.text = words
But
It says it can't convert [String] to string
It prints all of the words
You can try
label.text = words.first ?? "No words"
or
label.text = words.randomElement() ?? "No words"
words is an array of type String so you can't assign it directly to the text property of the label which is of type String
Related
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)
}
}
var pickerData: [[String]] = [String]
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
// Connect data:
self.gothramPicker.delegate = self
self.gothramPicker.dataSource = self
pickerData = [
[["A"],["i","ii","iii"]],
[["B"],["iv","v","vi","vii"]]
]"
getting error of Contextual type 'String' cannot be used with array literal.
my picker has two sections and each item if selected in the first picker has its own subdivisions to select from the second picker.
I want to use Array in Array and each main array has subarrays of different list. When I select first array in the picker it should show only the subitems of the particular Array item. For which when I add the double Brackets, I am getting the error. Also please let me know any error in the code
#sureshtrb , I am not posting answer because you don't asked question here. Frankly, you are troubling in Syntax understanding only.
You were declaring picketData of type Array([]) that contains array of string[[String]], and by putting ["A"] in place of string, you are adding an array ["A"] in place of String "A".
As per your real problem, I suggest you to go with 2 diff array or use dictionary.
The below code compiles.
var pickerData: [[String]] = [[String]]()
override func viewDidLoad() {
super.viewDidLoad()
pickerData = [
["A","i","ii","iii"],
["B","iv","v","vi","vii"]
]
}
Let's say I have a variable of type String holding a single String. In this string, there are 1 or more words. I also have an array of Strings. I want to check the String against the array, looking for, and replacing words found in the array.
For instance, the word "able" is in the array. The word "able" is also in the String variable. I want the word able replaced with the "+" character.
I've tried like this:
//stopWords = array of Strings / keywords = String variable
for words in stopWords {
keywordsFormatted = keywords.replacingOccurrences(of: words, with: "+", options: .regularExpression, range: nil)
}
and that doesn't change anything. I've also tried in a while loop, and a few other ways that I don't even care to recall right now lol. Any help is appreciated
Given
let stopWords = ["red", "green", "blue"]
let keywords = "The sky is blue not green"
let's create a set
let stopWordsSet = Set(stopWords)
and finally let's solve the problem
let result = keywords
.components(separatedBy: " ")
.map { stopWordsSet.contains($0) ? "+" : $0 }
.joined(separator: " ")
Oh... and lets test it
print(result) // The sky is + not +
Please note this solution is case sensitive. Furthermore it will not work is words in keywords are not delimited by spaces. E.g. "The sky is blue, not green" will not work properly because of the ,.
Addendum from Adrian:
If you want to update the textField, just use didSet, like so:
var keywords = "The sky is blue not green" {
didSet {
// if keywords is not empty, set the myTextField.text to keywords
if !keywords.characters.isEmpty {
myTextField.text = keywords
}
}
}
I am currently struggling with obtaining a value from an array inside an array of dictionaries. Basically I want to grab the first "[0]" from an array stored inside an array of dictionaries. This is basically what I have:
var array = [[String:Any]]()
var hobbies:[String] = []
var dict = [String:Any]()
viewDidLoad Code:
dict["Name"] = "Andreas"
hobbies.append("Football", "Programming")
dict["Hobbies"] = hobbies
array.append(dict)
/// - However, I can only display the name, with the following code:
var name = array[0]["Name"] as! String
But I want to be able to display the first value in the array stored with the name, as well. How is this possible?
And yes; I know there's other options for this approach, but these values are coming from Firebase (child paths) - but I just need to find a way to display the array inside the array of dictionaries.
Thanks in advance.
If you know "Hobbies" is a valid key and its dictionary value is an array of String, then you can directly access the first item in that array with:
let hobby = (array[0]["Hobbies"] as! [String])[0]
but this will crash if "Hobbies" isn't a valid key or if the value isn't [String].
A safer way to access the array would be:
if let hobbies = array[0]["Hobbies"] as? [String] {
print(hobbies[0])
}
If you use a model class/struct things get easier
Given this model struct
struct Person {
let name: String
var hobbies: [String]
}
And this dictionary
var persons = [String:Person]()
This is how you put a person into the dictionary
let andreas = Person(name: "Andreas", hobbies: ["Football", "Programming"])
persons[andreas.name] = Andreas
And this is how you do retrieve it
let aPerson = persons["Andreas"]
I am trying to create a array to hold dictionaries.
var deaultScoreResults : [Dictionary<String, Int>] = [];
But when I try to add a dictionary key:value pair I get:
deaultScoreResults.append(["Study Up!", 1]);
Error;
Type 'Dictionary' does not conform to protocol
'ArrayLiteralConvertible'
Square brackets surrounding a comma separated list of values is an array literal.
["this", "is", "a", "swift", "literal", "array"]
For a literal dictionary, you need a comma separated list of key:value pairs:
[1:"this", 2:"is", 3:"a", 4:"swift", 5:"literal", 6:"dictionary"]
To fix the error, you simply need to change your comma to a colon:
defaultScoreResults.append(["Study Up!":1])
However, based on your previous question, I'm going to assume an array of <String, Int> dictionaries isn't anywhere near what you're looking for.
I would suggest that you want simply an <Int, String> dictionary:
var defaultScoreResults = Dictionary<Int, String>()
defaultScoreResults[1] = "Study Up!"
Try this:
var deaultScoreResults = [Dictionary<String, Int>]()
deaultScoreResults.append(["Study Up!":1])
You could also declare it like this:
var deaultScoreResults = [[String:Int]]()