Swift 'AnyObject' does not have a member named "make" - object

I am confused on how I can have two keys as strings and one works and the other doesn't. Error occurs in the line near the end:
println("Here's a (car.year) (car.make) (car.model)")
What is it about the "make" variable that could be causing the problem?
protocol NSCoding {
}
class Car:NSObject {
var year: Int = 0
var make: String = ""
var model: String = ""
override init() {
super.init()
}
func encodeWithCoder(aCoder: NSCoder!) {
aCoder.encodeInteger(year, forKey:"year")
aCoder.encodeObject(make, forKey:"make")
aCoder.encodeObject(model, forKey:"model")
}
init(coder aDecoder: NSCoder!) {
super.init()
year = aDecoder.decodeIntegerForKey("year")
make = aDecoder.decodeObjectForKey("make") as String
model = aDecoder.decodeObjectForKey("model") as String
}
}
class CarData {
func archiveData () {
var documentDirectories:NSArray
var documentDirectory:String
var path:String
var unarchivedCars:NSArray
var allCars:NSArray
// Create a filepath for archiving.
documentDirectories = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)
// Get document directory from that list
documentDirectory = documentDirectories.objectAtIndex(0) as String
// append with the .archive file name
path = documentDirectory.stringByAppendingPathComponent("swift_archiver_demo.archive")
var car1:Car! = Car()
var car2:Car! = Car()
var car3:Car! = Car()
car1.year = 1957
car1.make = "Chevrolet"
car1.model = "Bel Air"
car2.year = 1964
car2.make = "Dodge"
car2.model = "Polara"
car3.year = 1972
car3.make = "Plymouth"
car3.model = "Fury"
allCars = [car1, car2, car3]
// The 'archiveRootObject:toFile' returns a bool indicating
// whether or not the operation was successful. We can use that to log a message.
if NSKeyedArchiver.archiveRootObject(allCars, toFile: path) {
println("Success writing to file!")
} else {
println("Unable to write to file!")
}
// Now lets unarchive the data and put it into a different array to verify
// that this all works. Unarchive the objects and put them in a new array
unarchivedCars = NSKeyedUnarchiver.unarchiveObjectWithFile(path) as NSArray
// Output the new array
for car : AnyObject in unarchivedCars {
println("Here's a \(car.year) \(car.make) \(car.model)")
}
}
}

Use downcasting in your for loop. The compiler needs to know that car is of type Car and not just AnyObject.
for car in cars as [Car!] {
println("Here's a \(car.year) \(car.make) \(car.model)")
}

Related

How to iterate into the collection of class objects in node.js

I have two classes one and two
class One {
constructor(field1, field2) {
this.field1 = field1;
this.field2 = field2;
}
}
module.exports = one;
class Two {
constructor(field11, field22, list) {
this.field11 = field11;
this.field22 = field22;
this.list = list;
}
add(one) {
this.list.push(one);
}
}
module.exports = Two;
Third class imports both classes
const one= require('./one.js');
const two= require('./two.js');
Now, I have a function which creates an object of class two and add some values like,
two = new two();
two.add(new one(1,1000));
two.add(new one(2,2000));
console.log(two.list);
////list is a collection of class one object
Till this point is working fine, I am getting collection
My query is how to iterate through collection
like, I want to access
two.list[0].field1
// not getting the property field1
Try this:
class One {
constructor(field1, field2) {
this.field1 = field1; this.field2 = field2;
}
}
class Two {
constructor(field11, field22, list = []) {
this.field11 = field11; this.field22 = field22;
this.list = list
}
add(one) {
this.list.push(one);
}
}
two = new Two();
two.add(new One(1, 1000));
two.add(new One(2, 2000));
console.log(two.list);
There are some issues in code:
Naming and bracket is not closing correct
Default list parameter is also written in wrong format
class One {
constructor(field1, field2) {
this.field1 = field1;
this.field2 = field2;
}
}
class Two {
constructor(field11, field22, list = []) {
this.field11 = field11;
this.field22 = field22;
this.list = list;
}
add(one) {
this.list.push(one);
}
}
two = new Two();
two.add(new One(1,1000));
two.add(new One(2,2000));
console.log(two.list[0].field1);
Updated your code. Try running it

How to filter the values of a string array in a struct object substring wise

I want to check a value is there in section object.This code is working fine but if I write the complete name only it will get in to the filtered object.i need to get the filtered data when the search test matches with a substring in the string array
["A": ["Affenpoo", "Affenpug", "Affenshire", "Affenwich", "Afghan Collie", "Afghan Hound"], "B": ["Bagle Hound", "Boxer"]]
struct Objects {
var sectionName : String!
var sectionObjects : [String]
var sectionid:[String]!
var sectionph:[String]!
var sectionImage:[String]!
}
var objectArray = [Objects]()
var objectArrayFilter = [Objects]()
objectArrayFilter = objectArray.filter({$0.sectionObjects.contains(searchBar.text!)})
If you want filter like that if you enter string afg in UITextField then it should return only two object "Afghan Collie", "Afghan Hound" with section A, then you can make it like this.
objectArrayFilter = objectArray.flatMap {
var filterObjects = $0
filterObjects.sectionObjects = $0.sectionObjects.filter {
$0.range(of : searchBar.text!, options: .caseInsensitive) != nil
}
return filterObjects.sectionObjects.isEmpty ? nil : filterObjects
}
Edit: Struct that you have make is not proper what you need to do is make another struct and make with property object,id,ph and image all type of string and then make array of this struct inside your Object struct.
struct SubObjects {
var sectionObject: String!
var sectionid: String!
var sectionph: String!
var sectionImage: String!
}
struct Objects {
var sectionName : String!
var sectionObjects : [SubObjects]!
}
Now filter this way.
var objectArray = [Objects]()
var objectArrayFilter = [Objects]()
objectArrayFilter = objectArray.flatMap {
var filterObjects = $0
filterObjects.sectionObjects = $0.sectionObjects.filter {
$0.sectionObject.range(of : searchBar.text!, options: .caseInsensitive) != nil
}
return filterObjects.sectionObjects.isEmpty ? nil : filterObjects
}
Please try the following :
objectArrayFilter = objectArray.filter { $0.sectionObjects.contains(where: { $0.contains(searchBar.text!) }) }

How to pause, not stop an app/program in Swift?

Ok, this question even mind boggled my Computer Science teacher because nothing we thought of worked.
Below is my code. Because I am retrieving data from Parse, there is a slight delay in actually getting that data. And computers being computers, the app keeps executing the code even if the Parse data hasn't been retrieved.
All I want to do is tell my app to stop executing code for, say 5 seconds, before continuing (this should allow the Parse data to be retrieved and catch up with the program).
I've tried using the sleep (time) function but it just stops the whole program for the time imputed (so the data retrieval from Parse is also put on hold). Also, putting in a useless for-loop does the exact same thing.
The reason why I ask this is because I am getting a nil value when I print test1.
Also, it looks like "No Results" is being printed so that means something is wrong with my fetching Core Data stuff....
import UIKit
import Darwin
import CoreData
class RegisterEmail: UIViewController {
var test1: Bool?
var userID: String!
override func viewDidLoad() {
super.viewDidLoad()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func shouldPerformSegueWithIdentifier(identifier: String!, sender: AnyObject!) -> Bool {
if identifier == "passEmail" {
var appDel:AppDelegate = (UIApplication.sharedApplication().delegate as AppDelegate)
var context:NSManagedObjectContext = appDel.managedObjectContext!
var request = NSFetchRequest(entityName: "Users")
request.returnsObjectsAsFaults = false
var results: NSArray = context.executeFetchRequest(request, error: nil)!
if(results.count > 0)
{
var res = results [0] as NSManagedObject
userID = res.valueForKey("userID") as String
}
var query = PFUser.query()
query.getObjectInBackgroundWithId(userID) {
(User: PFObject!, error: NSError!) -> Void in
if error == nil {
//NSLog("%#", User)
var checkEmail = User["emailVerified"] as Bool
println(checkEmail)
var appDel:AppDelegate = (UIApplication.sharedApplication().delegate as AppDelegate)
var context:NSManagedObjectContext = appDel.managedObjectContext!
var newEmail = NSEntityDescription.insertNewObjectForEntityForName("Email", inManagedObjectContext: context) as NSManagedObject
newEmail.setValue(checkEmail, forKey: "emailStatus")
context.save(nil)
} else {
NSLog("%#", error)
}
}
var appDel1:AppDelegate = (UIApplication.sharedApplication().delegate as AppDelegate)
var context1:NSManagedObjectContext = appDel1.managedObjectContext!
var request1 = NSFetchRequest(entityName: "Email")
request1.returnsObjectsAsFaults = false
var results1: NSArray = context1.executeFetchRequest(request1, error: nil)!
if(results1.count > 0)
{
var res1 = results1 [0] as NSManagedObject
test1 = res1.valueForKey("emailVerified") as Bool
}
else
{
println("No results")
}
println (test1) //NIL VALUE
if (test1 == false) {
let alert = UIAlertView()
alert.title = "Error"
alert.message = "The email you have provided has not been verified."
alert.addButtonWithTitle("Dismiss")
alert.show()
return false
}
else {
return true
}
}
// by default, transition
return true
}
}
An arbitrary delay time can be achieved with
-(void)performSelector: withObject: afterDelay: (NSObject)
but this is not the most efficient way tho do this by any means. because fetching the data might only take a split second on one occasion and many seconds or never on another. Instead you would be better looking at a completion block for pushing the data to print.

Converting Hand Written DI to Windsor Provided DI

For the past six or seven months I have been doing DI in some of my components as result they have grown to become little bit of complicated. In the past I have been creating Object graphs with hand written Factories. Since it is becoming unmanageable I am trying to move that code to Framework dependent DI(by code and not by some XML files). I am posting my Code as well as issues I am stuck with.
Here is my composition layer (it is big, so bear with me :) ):
IAgentFactory GetAgentFactory()
{
string errorMessage;
IDictionary<AgentType, ServiceParameters> agentFactoryPrerequisite = new Dictionary<AgentType, ServiceParameters>();
string restResponseHeaderStatus = MyConfigurationProject.GetConfigValue("RestResponseHeaderStatus", out errorMessage);
var service1Parameters = new ServiceParameters();
service1Parameters.BindingName = MyConfigurationProject.GetConfigValue("Service1WebHttpBindingConfiguration", out errorMessage).ToString();
service1Parameters.HeaderPassword = MyConfigurationProject.GetConfigValue("Service1HeaderPassword", out errorMessage).ToString();
service1Parameters.HeaderUserName = MyConfigurationProject.GetConfigValue("Service1HeaderUserName", out errorMessage).ToString();
service1Parameters.ResponseHeaderStatus = restResponseHeaderStatus;
service1Parameters.ServicePassword = MyConfigurationProject.GetConfigValue("Service1ServicePassword", out errorMessage).ToString();
service1Parameters.ServiceUrl = MyConfigurationProject.GetConfigValue("Service1URL", out errorMessage).ToString();
service1Parameters.ServiceUserName = MyConfigurationProject.GetConfigValue("Service1ServiceUserName", out errorMessage).ToString();
agentFactoryPrerequisite.Add(new KeyValuePair<AgentType, ServiceParameters>(AgentType.Service1, service1Parameters));
var agentFactory = new AgentFactory(agentFactoryPrerequisite);
return agentFactory;
}
protected DatalayerSettings GetDataLayerSettings()
{
var datalayerSettings = new DatalayerSettings();
datalayerSettings.ConnectionString = ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString;
datalayerSettings.MySchemaName = ConfigurationManager.AppSettings["MyDatabaseSchema"];
datalayerSettings.UpdatingUser = "Admin";
return datalayerSettings;
}
PostgersDAFactory GetPostGresDaFactory()
{
var datalayerSettings = GetDataLayerSettings();
return new PostgersDAFactory(datalayerSettings, "MyAssembly.PostgresDA", "MyDifferentAssembly.CommonDatalayer", "MyServiceLogPath");
}
public class PostgersDAFactory
{
readonly DatalayerSettings _datalayerSettings;
readonly string _assemblyName;
readonly string _logPath;
readonly string _mySecondAssemblyName;
public PostgersDAFactory(DatalayerSettings datalayerSettings, string assemblyName, string mySecondAssemblyName, string logPath)
{
_datalayerSettings = datalayerSettings;
_assemblyName = assemblyName;
_logPath = logPath;
_commonDaAssemblyName = commonDaAssemblyName;
}
public IDA1 GetDA1Instance()
{
var type1 = Type.GetType("MyAssembly.PostgresDA.ClassRealisingImplementation_For_DA1," + _assemblyName);
return (IDA1)Activator.CreateInstance(type1, _datalayerSettings, _logPath);
}
public IDA2 GetDA2Instance()
{
var type1 = Type.GetType("MyAssembly.PostgresDA.ClassRealisingImplementation_For_DA2," + _assemblyName);
return (IDA2)Activator.CreateInstance(type1, _datalayerSettings);
}
public IDA3 GetDA3Instance()
{
var type1 = Type.GetType("MyAssembly2.ClassRealisingImplementation_For_DA3," + _commonDaAssemblyName);
return (IDA3)Activator.CreateInstance(type1, _datalayerSettings);
}
}
public BaseFileHandler GetFileHandler(FileProvider fileprovider, MockedServiceCalculator mockedServicecalculator = null)
{
string errorMessage;
var postgresFactory = GetPostGresDaFactory();
var Da1Instance = postgresFactory.GetDA1Instance();
var fileSyncBusiness = new FileSyncBusiness(Da1Instance);
var interfaceConfiguratonParameters = fileSyncBusiness.GetInterfaceConfigurationParameters();
var servicePointDetailsSettings = new ServicePointDetailsSettings();
var nullDate = new DateTime(2099, 1, 1);
CommonValidations commonValidations;
if (mockedServicecalculator == null)
{
commonValidations = GetStubbedCommonValidations(nullDate);
}
else
{
commonValidations = GetCommonValidations_WithMockedServiceCalculator(nullDate, mockedServicecalculator);
}
switch (fileprovider)
{
case FileProvider.Type1:
var type1Adapter = new Type1Adaptor(false, nullDate);
servicePointDetailsSettings = GetUtiltaParameters(interfaceConfiguratonParameters);
return new Type1FileHandler(servicePointDetailsSettings, fileSyncBusiness, commonValidations, type1Adapter);
case FileProvider.Type2:
var type2Adapter = new Type2Adaptor(true, nullDate);
servicePointDetailsSettings.ApplicableParameters = MyApplicationCommonMethods.ConvertConfigurationTableToDictonary(interfaceConfiguratonParameters, "applicableintype2");
servicePointDetailsSettings.BadFileLocation = MyConfigurationProject.GetConfigValue("Type2BadFileLocation", out errorMessage);
servicePointDetailsSettings.DateFormat = MyConfigurationProject.GetConfigValue("Type2DateFormat", out errorMessage);
servicePointDetailsSettings.FailureFileLocation = MyConfigurationProject.GetConfigValue("Type2FailureFile", out errorMessage);
servicePointDetailsSettings.LogFileName = "Type2LogFile";
servicePointDetailsSettings.LogPath = MyConfigurationProject.GetConfigValue("Type2ErrorLog", out errorMessage);
servicePointDetailsSettings.MandatoryParameters = MyApplicationCommonMethods.GetDictonaryForMandatoryParameters(interfaceConfiguratonParameters, "applicableintype2", "mandatoryintype2");
servicePointDetailsSettings.SourceFileLocation = MyConfigurationProject.GetConfigValue("type2FileLocation", out errorMessage);
servicePointDetailsSettings.SuccessFileLocation = MyConfigurationProject.GetConfigValue("type2SuccessFile", out errorMessage);
servicePointDetailsSettings.TargetFileExtension = MyConfigurationProject.GetConfigValue("type2SupportedFileType", out errorMessage);
servicePointDetailsSettings.Type2RecordTag = MyConfigurationProject.GetConfigValue("MyApplicationtype2RecordTag", out errorMessage);
return new Type2FileHandler(servicePointDetailsSettings, fileSyncBusiness, commonValidations, type2Adapter);
default:
throw new NotImplementedException("FileProvider type: " + Convert.ToInt32(fileprovider) + " is not implemented");
}
}
}
While moving towards Windsor, I am facing several issues, as I have never used this product, it seems it is very complicated.
Issues:
How to pass parameters to object when they have parameterised
constructors?
I know there is a better way to write this "PostgersDAFactory"
class, but simply don't know.
There are some Factory methods Such as GetAgentFactory(), which are
dependent on some static method of other project, which in turn
gives me configuration values(I ahd to store them in the database),
another method GetDataLayerSettings is dependent on app config as
well as some static string.
I am likely to change parameter names in my classes in order to
promote readability, so how to turn on the logging for Windsor?
Finally another complicated method GetFileHandler, has some logic
(switch case).
I have tried going on there website but I found it totally difficult to digest information, there API is huge and learning curve seems to be mammoth.
Note: I had to change the variable names due to security reasons.

ActionScript3 - augmenting prototype of String

In AS2 I could do the following:
String.prototype.startsWith = function(s){
return this.indexOf(s) == 1
}
thus, startsWith is available on every String object
var s = "some string to test with";
s.startsWith("some") // returns true
and did it with great repository of cool tools:
var s = "some #VAR string";
s.startsWith("some");//returns true
s.endsWith("ing");//returns true
s.contains("#");//returns true
s.dataBind({VAR: "awsome"})// returns 'some awsome string'
s = "b";
s.isAnyOf("a","b","c"); //true, because "b" is one of the options
s.isInArr(["a","b","c"]); //true, because "b" is in the passed array
var o = { foo: function(i) { return "wind " + i } }
s = "foo";
f.call(o,3) //returns "wind 3" because method foo is ivoked on o with 3
f.apply(o,[3]) //returns "wind 3" because method foo is ivoked on o with 3
var a1 = [], a2 = []
s.push(a1,a2) // pushes s into a1 and a2
And so on, and so forth with many cool things that makes coding much more fun (and blazing fast when smartly used)
It's not just about String, I have such utils for Number, Date, Boolean, and so on.
Here's what I tried:
[Test]
public function test_stringPrototype()
{
String.prototype.startsWith = function(s):Boolean
{
return return this.indexOf(s) == 1;
}
assertTrue( !!String.prototype.startsWith ) //and so far - so good ! this line passes
var s:String = "some str";
assertTrue(!!o.startsWith ) //and this won't even compile... :(
}
And this won't even compile, not to mention pass or fail the test...
error: Access of possibly undefined property startsWith through a reference with static type String.
Whats the way to do it in AS3?
you could always have the utility class that will collect all those methods and work on the string, e.g.
package utils
{
public class StringUtils
{
public static function startsWith(input:String, test:String):Boolean
{
return input.indexOf(test) == 0;
}
}
}
usage:
trace(StringUtils.startWith("My string", "My"));
or as a "global" function:
package utils
{
public function startsWith(input:String, test:String):Boolean
{
return input.indexOf(test) == 0;
}
}
usage:
trace(startWith("My string", "My"));
best regards
Yes of course, use string representation of a variable name: "startsWith"; Example down
String.prototype.traceME = function():void
{
trace(this);
}
var s:String = "some str";
s["traceME"]();
else method:
var s:Object = new String("some str");
s.traceME();

Resources