How can I assign nil to a binding object in SwiftUI? - binding

I want to default returnGroup as nil inside the init method , but I get the follow error
Nil default argument value cannot be converted to type 'Binding'
Would like to know how to set the binding to nil ?
class DisplayPlayGroupViewModel: ObservableObject {
#Binding var closeFlag : Bool
#Binding var returnGroup : PlayGroup?
init(closeFlag : Binding<Bool> , returnGroup : Binding<PlayGroup?> = nil){ //<----Error
self._closeFlag = closeFlag
self._returnGroup = returnGroup
}

If you want to assign nil to the binding set it using .constant(nil). Here's how you can do it.
init(closeFlag : Binding<Bool> , returnGroup : Binding<PlayGroup?> = .constant(nil)) {
self._closeFlag = closeFlag
self._returnGroup = returnGroup
}

Related

Swift Struct unable to set array elements above 0

I have following Swift struct:
struct MainStruct : Decodable{
var array : [InternalArray]?
}
struct InternalArray : Decodable{
var firstName : String?
var lastName : String?
var Number : Int?
}
And this is how I'm using it:
var testing: MainStruct? = MainStruct()
testing?.array = []
testing?.array!.append(InternalArray())
testing?.array![0].firstName = "TEST"
testing?.array![1].firstName = "TEST 1" - error: Execution was interrupted, reason: EXC_BAD_INSTRUCTION
It seems to work fine when I'm setting array element [0] but when I try to set element [1] I get an error. Maybe somebody know what is wrong with my implementation ?
The problem is you only have 1 item (index 0).
Let's unpack this, first we unwrap your option MainStruct in the testing variable, and unwrap the optional array:
if let unwrappedTestingMainStruct = testing,
let unwrappedArray = unwrappedTestingMainStruct.array {
unwrappedArray.count // = 1
}
You then try to access testing?.array![1] which would be the second item in the array… which doesn't exist.
If you just had the line:
testing?.array![1]
you would see the same error

Check if an element is present in 3D array Swift

I have an array which gets instantiated in viewDidLoad like var bookingsArray : [[String]] = []
I am adding elements to it in this way:
var configuration: [String] = []
configuration.append(textfieldFacility.text!)
configuration.append((pickSlotTF.text?.components(separatedBy: " ")[0])!)
configuration.append((pickSlotTF.text?.components(separatedBy: " ")[1])!)
bookingsArray.append(configuration as [String])
bookingsArray looks like :
[["A", "20-08-2017", "14:00"], ["B", "20-08-2017", "14:00"]]
While adding new elements to bookingsArray, I want to check if the new element is already present in the array. How do I do it in this case of multi-dimensional array?
First of all, if you want unique objects use a Set.
If this is not possible I highly recommend to use a custom struct which can conform to Equatable rather than a nested array , for example
struct Booking : Equatable {
let facilty : String
let date : String
let time : String
static func ==(lhs : Booking, rhs : Booking) -> Bool {
return lhs.facilty == rhs.facilty && lhs.date == rhs.date && lhs.time == rhs.time
}
}
Then declare the array as
var bookingsArray = [Booking]()
and create an object with
let dateArray = pickSlotTF.text!.components(separatedBy: " ")
let configuration = Booking(facility: textfieldFacility.text!,
date: dateArray[0],
time = dateArray[1])
bookingsArray.append(configuration)
The huge benefit is that you can easily check
if bookingsArray.contains(item)
You can simply search for it with contains().
var configuration: [String] = []
configuration.append(textfieldFacility.text!)
configuration.append((pickSlotTF.text?.components(separatedBy: " ")[0])!)
configuration.append((pickSlotTF.text?.components(separatedBy: " ")[1])!)
if !bookingsArray.contains(where: {$0 == configuration}) {
bookingsArray.append(configuration)
}

How to declare an empty array of type 'CNLabeledValue' using Swift 3?

The code that used to work in iOS 9 was:
var valuesArray : [CNLabeledValue] = []
But I can't figure out how to do it in Swift 3.
This is the solution:
var phoneNumbers : [CNLabeledValue<CNPhoneNumber>] = []
As OOPer pointed out in this post:
CNLabeledValue's generic parameter is declared as <ValueType : NSCopying, NSSecureCoding>. So, in this case, you can choose any type which conforms to NSCopying and NSSecureCoding. NSString does and String does not.
something like this (with example to fill out phone number):
let phonesArray : [Phones] = phones!
var phonesToAdd = [CNLabeledValue]()
for phone in phonesArray
{
if let phoneT = phone.phoneType
{
if phoneT.lowercaseString == "mobile"
{
let mobilePhone = CNLabeledValue(label: "mobile",value: CNPhoneNumber(stringValue: phone.phone))
phonesToAdd.append(mobilePhone)
}
if phoneT.lowercaseString == "landline"
{
let landlinePhone = CNLabeledValue(label: "landline",value: CNPhoneNumber(stringValue: phone.phone))
phonesToAdd.append(landlinePhone)
}
}
}
contactData.phoneNumbers = phonesToAdd

get variable data from a class - swift

So, i have a file data.swift with some informations
class Data {
var agen = [… ]
var tours = [… ]
var marseille = [… ]
……
}
In another viewcontroller, i m trying to get back a value from above with this.
I can get back a particular value with with command with success :
let entry = data.agen[indexPath.row]
It’s working but I would like set a variable in this command, I put this
var passedValue:String!
// passedValue coming from a segue from a previous VC
// passedValue could be "agen", "tours",”marseille” ...
let entry = data.passedValue[indexPath.row]
But it's not working message error told me "data doesn't have a member named "passedValue"
How could i set properly the variable ?
what about a slightly different syntax
class Data {
var agen = ["A","B","C"]
var tours = ["D","E"]
var marseille = ["F","G","H"]
subscript(index: String) -> [String]! {
switch index {
case "agen" : return agen
case "tours" : return tours
case "marseille" : return marseille
default: return []
}
}
}
let key = "agen"
let data = Data()
print(data[key][1])
(maybe make a bit more error prof)
Other solution is to create classes/structs for 'agen','tours', etc.
And set it in the Data object
class Data {
var agen = [Agen(title), Agen(title2)]
var tours = [Tour(title), Tour(title2)]
…… }
Because, probably you want to show some info about the object in tableView later, so you could go like this:
title.text = tour.title
subtitle.text = tour.placeName
imageView.image = tour.photos[1]

How to Deal with Default Initializer when variable are not initialized Using Struct

I'm using swift struct and trying to use its default initializer when my struct variables are not initialize, I try both non-optional and optional variables but in its only showing "memberwise Initializer".
below is example with optional variables
struct myFirstStruct {
var value1:String?
var value2:String?
}
below is example with non-optional variables
struct myFirstStruct {
var value1:String
var value2:String
}
and it only gives
myFirstStruct(value1: <#String?#>, value2: <#String?#>)
and i want to use myFirstStruct()
help me. :)
Xcode is only showing you the 'member-wise' initialiser, but it's perfectly valid to use myFirstStruct(), passing no arguments, because all your variables have default values.
struct myFirstStruct {
var value1:String?
var value2:String = "InitialString"
}
let s1 = myFirstStruct()
// value1 = nil, value2 = "InitialString"
let s2 = myFirstStruct(value1: "Hello", value2: "World")
// value1 = "Hello", value2 = "World"
Need to set default value.
struct myFirstStruct {
var value1:String? = nil
var value2:String? = nil
}
let object = myFirstStruct()

Resources