Alright, so I'm building an app that takes in a sequence of int values using a text field and encrypts it depending upon the initialized cipher. Originally I use the .toInt() function to covert my numerical string values into an array of integer. Then I add the cipher to each value in the array of integers however I'm having difficulty outputting the int array back to the text-field with the encrypted sequence. I have already thoroughly researched this and I can't seem to find an adequate function to convert my int array (named: code) back into a string which I can initialize as message1.text = the string numerical sequence.
Here is my code so far:
class ViewController: UIViewController {
#IBOutlet var text: UITextField!
#IBOutlet var Lable: UILabel!
#IBOutlet var Button: UIButton!
#IBOutlet var message1: UITextField!
#IBOutlet var Button2: UIButton!
var name = 0
#IBAction func Button(sender: UIButton) {
name = text.text.toInt()!
}
#IBAction func Button2(sender: UIButton) {
var code = Array (message1.text).map{String($0).toInt()! }
for var n = 0 ; n < code.count; n++
{
code[n] = code[n] + name
}
var StringArray = (code : String()) // This is the mistake, I want to convert the code array into a joint string,
message1.text = StringArray
}
I already know that what I attempted to do doesn't work cause when I run the app and press Button2 I'am left with no text at all in the text-field thus it is a legitimate statement that String array is not being initialized as expected.
Any help is much appreciated, Thank you for your time I'm starting off in app programming and I'm still struggling at relatively simple stuff so I understand if the answer might seem overly palpable.
All you need to do is remap the values back to strings and join them:
var stringOfCodes = "".join( code.map { "\($0)" } )
This gives you a single string from the code values. I feel like there is a more elegant way to accomplish this, but this is what immediately came to mind.
If you want to create a string out of an array:
var spaceSeparatedString = " ".join(StringArray)
This will create a string out of the array using a space as the separator. Eg: "string1 string2 string3".
Related
Here's what I have so far:
import UIKit
class ViewController: UIViewController {
#IBOutlet weak var game1: UITextField!
#IBOutlet weak var game2: UITextField!
#IBOutlet weak var game3: UITextField!
#IBOutlet weak var series: UILabel!
#IBOutlet weak var average: UILabel!
#IBOutlet weak var high: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
#IBAction func calculate(_ sender: Any) {
let game1Results = Int(game1.text!)
let game2Results = Int(game2.text!)
let game3Results = Int(game3.text!)
let gameResultsArray = [game1Results, game2Results, game3Results]
high.text = "\(gameResultsArray.max())"
}
}
I've been trying to use the .max function but I'm getting errors stating I need to refer to conform to "Comparable". I'm pretty new to swift, any help will be much appreciated.
It happens because you try to compare values of optional Int (Int?)
First of all, you should know that not each String can be converted to an Int
E.g. '42' will be converted correctly, but 'ie42zx' can't be converted to and Int - that's why Int(String) function returns optional Int (Int?)
'Optional' property says like 'i can have a value, but I can also be nil'. That's why you should unwrap optionals in your code
First, I suggest to avoid force unwraping here.
let game1Results = Int(game1.text!)
It can be done like that:
guard
let text1 = game1.text,
let text2 = game2.text,
let text3 = game3.text
else { return }
You should do that because not every text field contains text, so textField.text property returns an optional String?
Then you can convert your String results to an Int and unwrap these results before compare:
guard
let game1Results = Int(text1),
let game2Results = Int(text2),
let game3Results = Int(text3)
else { return }
I would suggest to read more about optionals in swift and unwrapping (see Optionals paragraph)
I believe your issue is that the Int constructor with a string returns an optional integer value. You're trying to take the max of a bunch of optionals, so it cant figure it out.
You can use the compactMap function on your array before calling max() to filter out the nil values.
gameResultsArray.compactMap{ $0 }.max()
I'm trying to make an app that multiplies a number for a price that can be decimal or not. For example 3 * 3.50.
I'm using Swift 3. I searched for several topics here but could not add this feature to my app.
My code looks like this:
#IBOutlet weak var valueBreja1: UITextField!
#IBOutlet weak var quantityBreja1: UITextField!
#IBOutlet weak var totalBreja1: UILabel!
#IBAction func calcBreja1(_ sender: Any) {
let a = Int(valueBreja1.text!)
let b = Int(quantityBreja1.text!)
let Answer = a! + b!
totalBreja1.text = "R$\(Answer)"
}
I wanted to show the value with decimal number after multiplication.
Use Double instead of Int:
#IBAction func calcBreja1(_ sender: Any) {
let a = Double(valueBreja1.text!)
let b = Double(quantityBreja1.text!)
let Answer = a! + b!
totalBreja1.text = "R$\(Answer)"
}
You have two problems.
First, you're creating Int values from the field strings. Int values can only hold integer values, so any fractional portion will be discarded. You need to create Double values (or some other form of floating or fractional value).
To format the output use a formatter.
//: Playground - noun: a place where people can play
import Cocoa
var str1 = "3.50"
var str2 = "3"
if let value = Double(str1) {
if let multiplier = Int(str2) {
let formattedResult = String(format: "%.02f", value*Double(multiplier))
}
}
I am trying to pass data from textfield, back to previous controller using delegation. I am stuck when I try to assign Int value in this call.
This problem is fairly easy, however I cannot find a simple solution. I have been trying different approaches with additional properties that should hold this value, but with no succeed. What do I have to do with this budgetAmount.text to be properly converted?
protocol BudgetDelegate: class {
func enteredBudgetData(info: String, info2: Int)
}
class AddBudgetViewController: UIViewController {
var budget: Budget?
weak var delegate: BudgetDelegate? = nil
#IBOutlet weak var budgetName: UITextField!
#IBOutlet weak var budgetAmount: UITextField!
//
#IBAction func saveContent(_ sender: UIButton) {
if ((budgetName.text?.isEmpty)! && (budgetAmount.text?.isEmpty)!) {
navigationController?.pop(animated: true)
} else {
-> delegate?.enteredBudgetData(info: budgetName.text!, info2: budgetAmount.text!)
navigationController?.pop(animated: true)
}
}
}
Error Cannot convert value of type 'String' to expected argument type 'Int'
The info2 parameter of your protocol method is of type Int but you are passing budgetAmount.text! which is of course a String. You need to pass an Int.
Perhaps you need to convert the text in the textfield to an Int.
delegate?.enteredBudgetData(info: budgetName.text!, info2: Int(budgetAmount.text!) ?? 0)
BTW - you are making several terrible uses of the ! operator. You should spend time learning about optionals and how to safely work with then.
So based on your question, you just want to pass an Int data coming from a UITextField. And based on your description, you do not have any problem with delegation.
Converting a String into an Int is easy:
Example:
let num = "1"
if let intNum = Int(num) {
// There you have your Integer.
}
I am new to swift, so apologies for funny question, but I am quite tanged in this optional type and the unwrapping thing.
So, I am trying to create a calculator for which I have a UITextField to display the digits while pressed or result after calculation and off course some buttons representing digits.
Now I have action methods attached which my digit buttons and return button properly.
I have my UITextField declared like following which is implicitly unwrapped and a mutable string array which is also unwrapped-
#IBOutlet weak var displayTextField: UITextField!
var digitArray : [String]!
The append digit method works fine which just take the digit from the button and displays it in the textfield by appending. But I am getting a Bad Access error in the enter method. I guess, I am trying to add the item in the array improperly. Can anyone please help.
#IBAction func appendDigit(sender: UIButton) {
let digit = sender.currentTitle!
displayTextField.text = digit + displayTextField.text
}
#IBAction func enter(sender: UIButton) {
digitArray.append(displayTextField.text)
}
digitArray is declared but not initialized.
var digitArray = [String]()
The initializer syntax is either a pair of parentheses after the type let x = Type() or in case of an array with the type annotation and a pair of square brackets let x : [Type] = [].
As the compiler infers the type, the declaration [String] is not needed.
Declare variables non optional whenever possible, you will get more and better help by the compiler.
Convert initializer to
var digitArray = [String]()
I'm new to programming and after doing some tutorials online I decided to make my own app with Xcode 7 to be able to run my app on my iPhone. But when I try to get input data from a text field and put it into a var it gives me an error. I have tried to use the following:
var initialChips = 0
var initialBlind = 0
#IBOutlet weak var txtBlind: UITextField!
#IBOutlet weak var txtChips: UITextField!
#IBOutlet weak var doneBtn: UIBarButtonItem!
#IBAction func doneBtn(sender: AnyObject) {
let initialChips:Int? = Int(txtChips.text)
let initialBlind:Int? = Int(txtBlind.text)
}
Xcode will ask to put a "!" after ".text" but after doing that it gives me a warning: "Initialization of immutable value 'initialChips' (or 'initialBlind' was never used: consider replacing with assignment to '_'or removing it".
What can I do to set a value to my var?
The thing is that the let initialChips:Int? = Int(txtChips.text) generates a new variable called initialChips (different from the variable from the class). The difference between let and var is that let is inmutable and var is not. You should do:
initialChips = Int(txtChips.text)
To assign the integer from the UITextField to your class variable rather than declaring a new inmutable variable (with the same name) and do nothing with it.
Of course, the same happens with initialBlind
EDIT:
Try the following:
#IBAction func doneBtn(sender: AnyObject) {
if let initialChips = Int(txtChips.text!) {
self.initialChips = initialChips
}else {
self.initialChips = 0
}
if let initialBind = Int(txtBind.text!) {
self.initialBind = initialBind
}else {
self.initialBind = 0
}
}
You should add the ! after the closing parenthesis, not after .text, like so:
let initialChips:Int? = Int(txtChips.text)!