How Accss JsonData from given image - ios

array product modeldetail models
My code:
productDetailsNameLabel.text = products[indexPath.section].arr_details?[indexPath.item].productname
Getting error message:
Type Arr_Details has no subscripts member

arr_details not have any subscript members so you cannot access it. Please refer following example:
class Abc: NSObject {
var arr: [Xyz] = []
override init() {
for i in 1...5 {
arr.append(Xyz(number: i))
}
}
}
class Xyz: NSObject {
var number: Int
init(number: Int) {
self.number = number
}
}
// Use of this class
var arrAbc: [Abc] = []
for _ in 0...5 {
arrAbc.append(Abc())
}
yourLabel.text = "\(arrAbc[0].arr[0].number)"

arr_details doesn't have a subscript so that it doesn't return a value.
In order to use the subscript, you have to implement it on the arr_detail type.

Related

Does swift type inference not work with function return types?

Does swift type inference not work with function return types?
protocol Vehicle {
func numberOfWheels() -> Int
}
struct Car: Vehicle {
func numberOfWheels() -> Int {
return 4
}
}
struct Bike: Vehicle {
func numberOfWheels() -> Int {
return 2
}
}
struct Truck: Vehicle {
func numberOfWheels() -> Int {
return 8
}
}
struct VehicleFactory {
static func getVehicle<T: Vehicle>(_ vehicleType: T.Type = T.self) -> T? {
let id = identifier(for: T.self)
switch id {
case "Car":
return Car() as? T
case "Bike":
return Bike() as? T
default:
return nil
}
}
private static func identifier(for type: Any.Type) -> String {
String(describing: type)
}
}
let v: Bike = VehicleFactory.getVehicle() // ERROR HERE: Cannot convert value of type 'T?' to specified type 'Bike'
print(v.numberOfWheels())
I am trying this in playground. Why is there an error in above line?
Shouldnt the compiler infer the type to be Bike from the let v: Bike declaration?
The problem is that getVehicle returns an optional, you have to declare
let v: Bike? = VehicleFactory.getVehicle()
Further you have to unwrap v in the print line
Not a direct answer to your question. Vadian has already answered but a few notes on your implementation:
(_ vehicleType: T.Type = T.self) is pointless. You can just omit it.
Second I would simply add init() to your protocol requirements, get rid of the identifier method, change number of wheels to a computed property:
protocol Vehicle {
init()
var numberOfWheels: Int { get }
}
struct Car: Vehicle {
let numberOfWheels = 4
}
struct Bike: Vehicle {
let numberOfWheels = 2
}
struct Truck: Vehicle {
let numberOfWheels = 8
}
struct VehicleFactory {
static func getVehicle<T: Vehicle>() -> T { .init() }
}
let v: Bike = VehicleFactory.getVehicle()
print(v.numberOfWheels) // "2\n"

Extending CollectionType with optional initialiser

protocol Decodable {
init?(data: [String: AnyObject])
}
struct A: Decodable {
var data: [String: AnyObject]!
init?(data: [String: AnyObject]) {
self.data = data
}
}
This works when i want to create an object
let d = ["name":"Rahul"]
let a = A(data: d)
I am trying to achieve the following but it is giving errors at the compile time.
let dArray = [["name":"Rahul"],["name":"Rahul"],["name":"Rahul"]]
let aArray = [A](data: dArray)
The following code is giving me error 'nil is the only return value permitted in an initializer'.
public extension CollectionType where Generator.Element: Decodable {
init?(data: [[String: AnyObject]]) {
var elements: [Generator.Element] = []
for d in data {
let element = Generator.Element(data: d)
if let element = element {
element.append(element)
}
}
return elements
}
}
=================================
Answer : -
public extension Array where Element: Decodable {
init?(data: [String: AnyObject]) {
var elements: [Element] = []
for d in data {
let element = Element(data: d)
if let element = element {
element.append(element)
}
}
self = elements
}
}
This will allow you to initialise using the following code
let dArray = [["name":"Rahul"],["name":"Rahul"],["name":"Rahul"]]
let aArray = [A](data: dArray)
Your error is because CollectionType is a protocol, which cannot be initialised.
Have you tried to create a helper class method to return you the collection, e.g.
func collectionWithData(data: [[String: AnyObject]]) -> [Generator.Element] {
let's define a protocol
protocol P {
init?(b: Bool)
}
as mentioned by Oliver, protocol cannot be initialized, but we still are able to define init in protocol extension
extension P {
init?(b: Bool) {
print("init defined in extension")
if b == false { return nil }
self.init(b: b)
}
}
see, that you cannot return anything from init but nil (if initialization failed)
let's define a class which conforms to our protocol
class C: P {
var b: Bool
required init(b: Bool) {
self.b = b
}
}
and see what happens in next snippet
let c1: C? = C(b: false)
let c2 = C(b: false)
dump(c1)
dump(c2)
/*
init defined in extension
- nil
▿ C #0
- b: false
*/
the same expression C(b: false) give us two different results :-). So, be careful if you define init and init? via protocol extension. If you try to define init and init? with the same parameters without protocol extension, the compiler will complain.

Swift 2 Correct way to get level of any object game, protocol? struct? extension?

This is my first game, and I'm new on swift and sprite kit.
I must have a level for each class that needs get level. Like car lev1 car lev 2 etc. I have read about protocol extension etc, witch is the best way to approach level management?
I have tried to use LevelTraker as extension of this protocol:
protocol LevelTracker {
typealias TypeUnit: TypeGame
var nameClass: String! {get set}
var currentLevel : Int {get set}
mutating func levelIncreases()
}
but with extension, i must write 3 var each class that needs level.
i try the same extension LevelTraker with struct LevelTraker:
func getClassName (theClass:AnyObject) -> String {
let name = _stdlib_getDemangledTypeName(theClass); return name}
protocol TypeGame {}
enum transportType : TypeGame {
case ground, sea, air
}
struct LevelTracker {
var sender: AnyObject
var TypeUnit: TypeGame
private func getSaveFileWhitName() -> String {
let saveWithName = getClassName(sender) + "." + String(TypeUnit)
return saveWithName
}
var currentLevel : Int {
get {
let stringName = getSaveFileWhitName()
let returnValue : Int = dataBase.read(stringName) as? Int ?? 1 //Check for first run of app, if = nil, set = 1
return returnValue
}
set (newValue) {
let stringName = getSaveFileWhitName()
let level : Int = self.currentLevel
let val = newValue
if (newValue > level) {dataBase.write(val, key: stringName)}
}
}
mutating func levelIncreases() {self.currentLevel++}
///SERVE SOLO PER SVILUPPO
mutating func RESETLEVEL() {dataBase.write(1, key: getSaveFileWhitName())}
}
To use: (thanks #Krzak)
class car {
init () {
let level = LevelTracker(sender: self, TypeUnit: transportType.ground).currentLevel
}
}
But I don't want modify all init object that use level, and the super super class in common, some class don't have propriety level.
The reason why you have compiler error is in your last line. You're missing the .ground
I'm not sure how you're thinking though that this will work, shouldn't it be var?
var level = LevelTracker(sender: self, TypeUnit: transportType.ground).currentLevel
What I am reading it sounds like you are doing this:
class Level : AnyObject
{
private func getSaveFileWhitName() -> String {
let saveWithName = getClassName(sender) + "." + String(TypeUnit)
return saveWithName
}
var currentLevel : Int {
get {
let stringName = getSaveFileWhitName()
let returnValue : Int = dataBase.read(stringName) as? Int ?? 1 //Check for first run of app, if = nil, set = 1
return returnValue
}
set (newValue) {
let stringName = getSaveFileWhitName()
let level : Int = self.currentLevel
let val = newValue
if (newValue > level) {dataBase.write(val, key: stringName)}
}
}
mutating func levelIncreases() {self.currentLevel++}
///SERVE SOLO PER SVILUPPO
mutating func RESETLEVEL() {dataBase.write(1, key: getSaveFileWhitName())}
}
class car : Level
{
init () {
let level = self.currentLevel
}
}
I found a solution, I'm happy to have some comment.
protocol TypeGame {}
enum transportType : TypeGame {
case car, bus, trak
}
protocol LevelTracker {
var nameClass: String! {get}
var currentLevel : Int {get set}
mutating func levelIncreases()
}
extension LevelTracker {
var currentLevel : Int {
get {/*set to DB*/ return 1}
set (newValue) {/*set to DB*/}
}
mutating func levelIncreases() {self.currentLevel++}}
A protocol only for transport object:
protocol Transport : LevelTracker {}
Ok, now my (simplified) class are:
class AllNode {//SKSpriteNode
init(){}
}
class TransportGame:AllNode, Transport {
var nameClass : String! = "Transport"
override init() {
super.init()
self.nameClass = nameClass + "." + getClassName(self)}
}
class Car : TransportGame {}
class miniCar : Car {}
class Bus: TransportGame {}
class Tree: AllNode {}
var carOne = Car()
let levelCar = carOne.currentLevel
var busOne = Bus()
let levelBue = busOne.currentLevel
var treeOne = Tree()
tree.currentLevel //ERROR YUPPI!!!! :)
Now the tree class can't access to level!
What do you think about this solution?

Generic constraint for any protocol in Swift

Is it possible to constrain generic type to accept protocol in Swift?
I have implemented wrapper to have weak list of objects, and I need to extend that to protocols.
protocol Incrementable: class {
func inc()
}
class Counter: Incrementable {
var n: Int = 0
func inc() {
n += 1
}
}
struct Weak<T: AnyObject> {
weak var value : T?
init (value: T?)
{
self.value = value
}
}
var cnt: Counter? = Counter()
let counters : [Weak<Counter>] = [Weak(value: cnt), Weak(value: Counter())]
for counter in counters
{
counter.value?.inc()
}
Now if I want to store any object that implements Incrementable I have to use AnyObject and that is not very type safe and also includes as? casting
let counters : [Weak<AnyObject>] = [Weak(value: cnt), Weak(value: Counter())]
for counter in counters
{
(counter.value as? Incrementable)?.inc()
}
And code I would like to have would be
let counters: [Weak<Incrementable>] = [Weak(value: cnt), Weak(value: Counter())]
for counter in counters
{
counter.value?.inc()
}
Of course, above code cannot be compiled and fails with:
Using 'Incrementable' as concrete type conforming to protocol
'AnyObject' is not supported
Is it possible to write Weak wrapper so it can accept and store weak references to protocol?
While root cause of my problem is same as in Using as a concrete type conforming to protocol AnyObject is not supported that question deals with hash tables and I need solution with lists that allows duplicate entries.
Following answer pointed me in right direction and I was able to come up with following solution for implementing weak list of protocol references that allows duplicates and nil (convenience) entries.
struct Weak<T>
{
weak var value: AnyObject?
init (value: T?)
{
if value != nil
{
guard value is AnyObject else { fatalError("Object (\(value)) should be subclass of AnyObject") }
self.value = value as? AnyObject
}
}
}
class WeakList<T>: SequenceType
{
var items : [Weak<T>] = []
func add(item: T?)
{
items.append(Weak(value: item))
}
func generate() -> AnyGenerator<T>
{
var nextIndex = items.count - 1
return anyGenerator
{
while nextIndex >= 0
{
let item = self.items[nextIndex--]
if item.value != nil
{
return item.value as? T
}
}
return nil
}
}
}
let incrementables = WeakList<Incrementable>()
incrementables.add(Counter())
incrementables.add(cnt)
incrementables.add(nil)
incrementables.add(Counter())
incrementables.add(cnt)
for counter in incrementables
{
counter.inc()
}

Generic class inheritance in Swift

I have the following class:
class BaseCache<T: Equatable>: NSObject {
var allEntities = [T]()
// MARK: - Append
func appendEntities(newEntities: [T]) {
....
}
}
Now I want to subclass it, but I get annoying error, that my type "does not conform to protocol 'Equatable'":
It seems generics in Swift are real pain-in-the-ass.
Your class definition of TrackingCache is wrong. It repeats the generic parameter:
class TrackingCache<AftershipTracking>: BaseCache<AftershipTracking> { }
It should be left out:
class TrackingCache: BaseCache<AftershipTracking> { }
This triggers the underlying swift error Classes derived from generic classes must also be generic. You can work around this issue by specifying a type parameter that is required to be or inherit from AftershipTracking:
class TrackingCache<T: AftershipTracking>: BaseCache<AftershipTracking> { }
Full example:
class BaseCache<T: Equatable>: NSObject {
var items: [T] = []
func appendItems( items: [T]) {
self.items += items
didAppendItems()
}
func didAppendItems() {} // for overriding
}
class AftershipTracking: NSObject {
var identifier: Int
init( identifier: Int) {
self.identifier = identifier
super.init()
}
}
extension AftershipTracking: Equatable { }
func ==( lhs: AftershipTracking, rhs: AftershipTracking) -> Bool {
return lhs.identifier == rhs.identifier
}
class TrackingCache<T: AftershipTracking>: BaseCache<AftershipTracking> {
override func didAppendItems() {
// do something
}
}
let a = TrackingCache<AftershipTracking>()
let b = TrackingCache<AftershipTracking>()
a.appendItems( [AftershipTracking( identifier: 1)])
b.appendItems( [AftershipTracking( identifier: 1)])
let result = a.items == b.items // true
this should work: < swift 4 >
class TrackingCache<T: AftershipTracking>: BaseCache<T>
Another example:
protocol P {
}
class C: P {
}
class CS: C {
}
class L<T:P> {
let c: T
init(_ c: T) {
self.c = c
}
}
class LS<T:CS>:L<T> {
}
let i = LS(CS())
i.c
c is CS now.

Resources