I want a matching array has codes
I've match one code it works without a problem
this code is works well
let code = "code"
if metadataObj.stringValue == code {
println("the code is true")
}else {
println("the code is false")
}
But when I try this code
var codes = ["a","b","c"]
if metadataObj.stringValue == codes {
println("the code is true")
}else {
println("the code is false")
}
This problem appears
cannot invoke == with an argument list of type
It works well with array var codes = ["a","b","c"] But when you put array of analysis JSON local file is not working
A string cannot be equal to an array.
If you want to test if the string is equal to one of the array elements
then use contains():
if contains(codes, metadataObj.stringValue) { ... }
Related
I have two UITextFields that get the placeHolder.text randomly from an array. The part I am stuck on, is having an element in an array of answers, correspond to the placeHolder text.
Meaning: placeHolder.text is a question, user text input is the answer, and we check that the user answer is the same as the hard coded value.
sample code:
let questionArray = ["name of your cat?", "name of your other cat?"]
let questionArray2 = { more stupid questions ]
let answerArray = ["cat damen", "diabetes"]
let answerArray2 = [ more stupid answers ]
var answerContainer: String()
var answerContainer2: String()
uitextField1.placeHolder = questionArray.randomElement()
uitextField2.placeHolder = questionArray2.randomElement()
Heres where I get stupid :
func answerGenerator {
if UItextField1.placeHolder == questionArray[0] {
answerContainer = answerArray[0]
}
}
func submit(_ sender: UIButton) {
if uitextField.text == answerContainer && uitextField2.text == answerContainer2 {
do good stuff
}
}
I tried using a dictionary, but got stuck. I also thought about an Enum / Switch Case, but also got stuck as I have two textFields that need the placeHolder generated randomly.
so what happens is the actual answer that's supposed to be allocated to its question, maybe it happens, but I'm not grabbing it correctly to compare what the user will type in the textfield.
Its so easy, but I'm overthinking this.
I'm learning Swift as I go here, so apologies if this is a silly question.
I'm looking to use the output of one function (String) to determine an input into a different function (Array).
The first function output (String) is then combined with another String to form the name of an already defined Array, which i'd like to use as input to second function. However, despite having the same name, the String is not seen as an array.
I've skipped some of the code, but relevant section below.
// Defined array
let rushProb = [0,11,19,64,78,89,96,98,99,100]
// Define probability and outcome function - PlayType
func findPlay(prob: [Int], outcome: [String]) -> String {
if let index = prob.firstIndex(where: { $0 > Int.random(in: 1...100) }) {
return outcome[index]
}
else {
return "na"
}
}
// This is successfully output as "rush"
let playSel = findPlay(prob: scen1Prob, outcome: scenPlay)
// This then creates "rushProb"
let playSelProb = playSel+"Prob"
// I want this to ultimately be findYards(prob: rushProb)
findYards(prob: playSelProb)
Well, you could use a dictionary where the key replaces your array name, and the value is the array. Then, you'd use the name you create to look up the array value in the dictionary:
let arrays = ["rushProb": [0,11,19,64,78,89,96,98,99,100],
"fooProb" : [0,15,29,44,68,78,86,92,94,100]]
// This is successfully output as "rush"
let playSel = findPlay(prob: scen1Prob, outcome: scenPlay)
// This then creates "rushProb"
let playSelProb = playSel+"Prob"
// look up the array that corresponds to "rushProb"
if let array = arrays[playSelProb] {
findYards(prob: array)
}
I tried to cast a swift protocol array as any array, but failed.
protocol SomeProtocol: class{
}
class SomeClass: NSObject, SomeProtocol{
}
let protocolArray: [SomeProtocol] = [SomeClass()]
let value: Any? = protocolArray
if let _ = value as? [SomeProtocol]{
print("type check successed") //could enter this line
}
Above code could work as expected.
However, my problem is, I have a lot of protocols, and I don't want to check them one by one. It is not friendly to add new protocol.
Is there any convenience way to do check if above "value" is a kind of array like below?
if let _ = value as? [Any]{
print("type check successed") //never enter here
}
edit:
Inspired by Rohit Parsana's answer, below code could work:
if let arrayType = value?.dynamicType{
let typeStr = "\(arrayType)"
if typeStr.contains("Array"){
print(typeStr)
}
}
But these code seems not safe enough, for example, you can declare a class named "abcArray".
Although we could use regular expression to check if "typeStr" matches "Array<*>", it seems too tricky.
Is there any better solution?
You can use reflection:
if value != nil {
let mirror = Mirror(reflecting: value!)
let isArray = (mirror.displayStyle == .Collection)
if isArray {
print("type check succeeded")
}
}
You can check the type of value using 'dynamicType', here is the sample code...
if "__NSCFArray" == "\(page.dynamicType)" || "__NSArrayM" == "\(page.dynamicType)"
{
print("This is array")
}
else
{
print("This is not array")
}
I read into myArray (native Swift) from a file containing a few thousand lines of plain text..
myData = String.stringWithContentsOfFile(myPath, encoding: NSUTF8StringEncoding, error: nil)
var myArray = myData.componentsSeparatedByString("\n")
I change some of the text in myArray (no point pasting any of this code).
Now I want to write the updated contents of myArray to a new file.
I've tried this ..
let myArray2 = myArray as NSArray
myArray2.writeToFile(myPath, atomically: false)
but the file content is then in the plist format.
Is there any way to write an array of text strings to a file (or loop through an array and append each array item to a file) in Swift (or bridged Swift)?
As drewag points out in the accepted post, you can build a string from the array and then use the writeToFile method on the string.
However, you can simply use Swift's Array.joinWithSeparator to accomplish the same with less code and likely better performance.
For example:
// swift 2.0
let array = [ "hello", "goodbye" ]
let joined = array.joinWithSeparator("\n")
do {
try joined.writeToFile(saveToPath, atomically: true, encoding: NSUTF8StringEncoding)
} catch {
// handle error
}
// swift 1.x
let array = [ "hello", "goodbye" ]
let joined = "\n".join(array)
joined.writeToFile(...)
With Swift 5 and I guess with Swift 4 you can use code snippet which works fine to me.
let array = ["hello", "world"]
let joinedStrings = array.joined(separator: "\n")
do {
try joinedStrings.write(toFile: outputURL.path, atomically: true, encoding: .utf8)
} catch let error {
// handle error
print("Error on writing strings to file: \(error)")
}
You need to reduce your array back down to a string:
var output = reduce(array, "") { (existing, toAppend) in
if existing.isEmpty {
return toAppend
}
else {
return "\(existing)\n\(toAppend)"
}
}
output.writeToFile(...)
The reduce method takes a collection and merges it all into a single instance. It takes an initial instance and closure to merge all elements of the collection into that original instance.
My example takes an empty string as its initial instance. The closure then checks if the existing output is empty. If it is, it only has to return the text to append, otherwise, it uses String Interpolation to return the existing output and the new element with a newline in between.
Using various syntactic sugar features from Swift, the whole reduction can be reduced to:
var output = reduce(array, "") { $0.isEmpty ? $1 : "\($0)\n\($1)" }
Swift offers numerous ways to loop through an array. You can loop through the strings and print to a text file one by one. Something like so:
for theString in myArray {
theString.writeToFile(myPath, atomically: false, encoding: NSUTF8StringEncoding, error: nil);
}
So I have a program that sends emails. The user has a list of emails that cannot be sent to. These are in arrays and I need to use a if statement to determine if what the user entered in is in the array of emails. I tried the in function which didnt work but Im probably just using it wrong. I tried for loops and if statements inside. But that didnt work either. Here is a snapshot of the code Im using to help you get the idea of what im trying to do.
function test2(){
var safe = [1]
safe[1] = "lol"
safe[2] = "yay"
var entry = "lol"
Logger.log("entry: " + entry)
for(i = 0; i < safe.length; i++){
if(entry == safe[i]){
Logger.log("positive")
}else{
Logger.log("negative")
}
}
}
Here is what I tried with the in function to show you if I did it wrong
function test(){
var safe = [1]
safe[1] = "lol"
safe[2] = "yay"
var entry = "losl"
Logger.log("entry: " + entry)
if(entry in safe){
Logger.log("came positive")
}else{
Logger.log("came negative")
}
Logger.log(safe)
}
array.indexOf(element) > -1 usually does the trick for these situations!
To expand upon this:
if (array.indexOf(emailToSendTo) < 0) {
// send
}
Alternatively, check this cool thing out:
emailsToSend = emailsToSend.filter(function(x) {
// basically, this returns "yes" if it's not found in that other array.
return arrayOfBadEmails.indexOf(x) < 0;
})
What this does is it filters the list of emailsToSend, making sure that it's not a bad email. There's probably an even more elegant solution, but this is neat.