How do I print Optional Int in SWIFT? - swift

I simply want to Print the optional humidityPercentage component of weather to the console.
let cityName: String
var humidityPercentage: Int?
var temperatureCentigrade: Int?
var weather = (weather.cityName= "GR", weather.humidityPercentage = 2,
weather.temperatureCentigrade = 2)
if let weather.humidityPercentage = weather.humidityPercentage {
print(weather.humidityPercentage)
}

Ya syntax is borked. Keep learning the syntax.
let weather = (
cityName: "GR",
humidityPercentage: 2 as Optional,
temperatureCentigrade: 2
)
if let humidityPercentage = weather.humidityPercentage {
print(humidityPercentage)
}

You can't have a . in the constant. Try this instead:
if let percentage = weather.humidityPercentage {
print(percentage)
}

Related

How to create a JSON in SWFT using users input data?

I need to create a JSON like this:
{
"var1": "1",
"var2": "2",
"newArray": [{
"Deleted": false
}]
}
My Codable looks like this:
struct RequestModel: Codable {
var var1: String?
var var1: String?
var Treatments: [Treat]
}
struct Treat: Codable {
var adminBy: String?
}
So, now I need to create the above JSON... I tried the following:
let adminBy = adminByTextField.text ?? ""
let VAR1 = var1TextField.text ?? ""
let VAR2 = var2TextField.text ?? ""
let dict = ["adminBy":adminBy] as! NSDictionary
///And I TRY to create my JSON here
private func createRequestObject() -> RequestModel {
let request = RequestModel(var1: VAR1,
var2: VAR2,
Treatments: dict)
return request
}
But I get this error:
I don't understand why this error occurs or how to fix it.
any advice would be appreciated.
You should not be using an NSDictionary here. You RequestModel object requires an array of Treat.
You could create the array in the following way and pass it to your RequestModel :
let adminBy = adminByTextField.text ?? ""
let VAR1 = var1TextField.text ?? ""
let VAR2 = var2TextField.text ?? ""
let treats = [Treat(adminBy: adminBy)]
let request = RequestModel(var1: VAR1, var2: VAR2, Treatments: treats)

Return a String from If statement in swift

I have this function to modify a string.
let offset = "01:00"
func newOffset() {
let offset12 = String(offset.prefix(1))
if offset12.contains("0") {
let offset13 = offset.suffix(4)
let offset14 = offset13.prefix(3).replacingOccurrences(of: ":", with: ".")
}
}
However I don't know how im supposed to get the value out of the function and assign it to a new variable. I want to be able to do something like this:
let offset2 = newOffset()
You need to take arguments in the function and return a string in the function too. Here is the code:
func newOffset(offset: String) -> String
{
let offset12 = String(offset.prefix(1))
if offset12.contains("0") {
let offset13 = offset.suffix(4)
let offset14 = offset13.prefix(3).replacingOccurrences(of: ":", with: ".")
return offset14
}
return offset
}
This worked for me:
var offset2 = ""
func newOffset() -> String {
let offset12 = String(offset.prefix(1))
if offset12.contains("0") {
let offset13 = offset.suffix(4)
offset2 = offset13.prefix(3).replacingOccurrences(of: ":", with: ".")
}
return(offset2)
}

swift - Array error

I'm trying to reads records from a .txt file and store them as a collection of structs but I am struggling to fix this error:
"Missing argument for parameter 'year' in call
This is my code:
struct DataSet: CustomStringConvertible {
var year: Int
var month: Int
var tmax: Double
var tmin: Double
var airfrost: Int
var rain: Double
var sun: Double
var description: String {
return "\(year) + \(month) + \(tmax) + \(tmin) + \(airfrost) + \(rain) + \(sun)"
}
}
let path = "/Users/sc16hsm/Desktop/CW2/data/bradford.txt"
var data = [DataSet]()
var temp = DataSet()
if let contents = try? String(contentsOfFile: path) {
let filtered = contents.components(separatedBy: "\n")
for line in filtered {
let x = line.components(separatedBy: " ").filter{$0 != ""}
let x = line.components(separatedBy: " ")
temp.year = Int(x[0])
temp.month = Int(x[1])
temp.tmax = Double(x[2])
temp.tmin = Double(x[3])
temp.airfront = Int(x[4])
temp.rain = Double(x[5])
temp.sun = Double(x[6])
data.append(temp)
print(x)
}
Any help would be greatly appreciated.
If the members of the struct don't have initial values you have to use the memberwise initializer. The default initializer doesn't work.
You have to write inside the loop
let temp = DataSet(year: Int(x[0])!,
month: Int(x[1])!,
tmax: Double(x[2])!,
tmin: Double(x[3])!,
airfrost: Int(x[4])!,
rain: Double(x[5])!,
sun: Double(x[6])!)
data.append(temp)
Please use code completion to get the complete syntax.

String.Index does not have a member named advancedBy

This is the swift code I have as an exercise from my class, I am re-writing it(as I am new to it).
At the position of
let end = starIndex.advancedBy(position), I am getting an error message of String.Index does not have a member named advancedBy I am not sure what this means or how to correct it just yet, many thanks for any help in understanding what I am doing wrong.
//: Playground - noun: a place where people can play
import UIKit
var str : String = "Hello, playground"
str
let strFix = " Can not change"
str = "Good bye"
//strFix = "Testing"
var str2 = str + "F"
var townName = "NeverLand"
let population = 30000
let numOfStopLight : Int = 10
print("\(townName) has populations of \(population)
and has \ (numOfStopLight) Stop Lights")
for c in townName.unicodeScalars
{
print ("\(c)")
}
let starIndex = str.startIndex
let position = 3
let end = starIndex.advancedBy(position)
let charAt = str[end]
let range = starIndex...end
str[range]
let aChar: Character = "\u{1F60E}"
str.append(aChar)
let dollarSign = "\u{24}" //$, Unicode scalar U+0024
let blackHeart = "\u{2665}" // , Unicode scalar U+2665
let sparklingHeart = "\u{1F496}" // , Unicod scalar U=1F496
str.append(Character(sparklingHeart))
for c in str.characters
{
print("\(c)")
}
for c in str.unicodeScalars
{
print("\(c.value)")
}
/////////////////////
struct Car
{
var make : String = ""
var price : Double = 0.0
let color : String = "RED"
func getMske()->String
{
return make
}
mutating func setMake (m: String)
{
make = m
}
func showCar()->String
{
return "Make:\(make) Price=\(price) Color= \(color)"
}
}
//let us make some Car
var myCar = Car(make: "Nissan", price: 45000.0)
print(myCar.showCar())
myCar.setMake("Nissan2016")
print (myCar.showCar())
//show pass value
func doChange (var c: Car)
{
c.setMake("Toyota")
print (c.showCar())
}
doChange(myCar)
print (myCar.showCar())
//let us have a class
class Xcar
{
var make :String = ""
var price : Double = 0.0
var color : String = ""
init(m :String, p: Double, c: String)
{
self.make = m
self.price = p
self.color = c
}
func setMake(m: String)
{
self.make = m
}
func showXCar()->String
{
return "Make: \(make) Price=\(price) Color=\(color)"
}
}
func doChangex( c:Xcar)
{
c.setMake("BMW")
print("\(c.showXCar())")
}
var hisCar = Xcar(m: "Fiat", p: 15000.0, c: "Blue")
print ("\(hisCar.showXCar())")
doChangex(hisCar)
//notice the function did change
//because it was a class
print ("\(hisCar.showXCar())")
//What is optional
let a: Float?
let b: Float?
let c :Float?
a = 10
b = 20
c = 5
//this is implicit unrap
let ave = (a! + b! + c!)/3.0
if let x = a, y = b, z = c
{
print ("\((x + y + z) / 3.0)")
}
else
{
print ("missing value...")
}
// note Array, Double, Float, Int and Dictionary are all struct
var intArray = [Int] ()
intArray.append(50)
intArray.append(100)
intArray.append(600)
intArray.maxElement()
intArray.capacity
intArray.count
intArray.description
intArray.dropFirst()
intArray.first
intArray.description
intArray.removeFirst()
intArray.description
for c in intArray
{
print("\(c)")
}
var dict = [Int :String ] ()
dict = [235 :"Jack", 100: "Joe", 60: "Lisa"]
dict.description
for(key, value) in dict
{
print ("\(key)")
}
var name = dict[235]
Try doing it in one line
let startIndex = str.startIndex.advancedBy(3)
The code has a number of issues and we don't know what the expected output is, but here are a few items:
The line with just 'str' on it should be removed.
You may be running an older version of Xcode or OS (or both). This is Swift2 and you should be using Xcode 7 or higher.
Also, there are 'var' that should be 'let' (hisCar) and there are a number of unused variables.
The good news is once you fix the issues that, the code runs correctly (as far as I can tell)

How do I set NSUserDefault settings as Instance Variables?

When I try to just set a constant based on the settings like below, it results in Optional("value").
let accesstoken = NSUserDefaults.standardUserDefaults().stringForKey("accessToken")
let userId = NSUserDefaults.standardUserDefaults().stringForKey("userId")
If I do it like the below, I get an error saying variable used within its own initial value. I can't seem to win here. What am I doing wrong?
var accesstoken = String()
var userId = Int()
if let atString = NSUserDefaults.standardUserDefaults().stringForKey("accessToken") {
accesstoken = atString
}
if let userIdString = NSUserDefaults.standardUserDefaults().stringForKey("userId") {
userId = userIdString
}
You can achieve what you want with a read only computed property combined with the nil coalescing operator "??". Try like this:
var accessToken: String {
return NSUserDefaults().stringForKey("accessToken") ?? ""
}
var userId: String {
return NSUserDefaults().stringForKey("userId") ?? ""
}
or if you need an Int for your userID
var userId: Int {
return NSUserDefaults().integerForKey("userId")
}