in Java the model looks like this:
public class Model {
private String nameLast = "";
private String nameFirst = "";
private String namePrefix = "";
private String nameSecond = "";
private String nameNick = "";
private String nameSuffix = "";
Model() {
}
public Model(String nameFirst, String nameSecond, String nameLast, String namePrefix, String nameSuffix, String nameNick) {
this.nameFirst = nameFirst;
this.nameSecond = nameSecond;
this.nameLast = nameLast;
this.namePrefix = namePrefix;
this.nameSuffix = nameSuffix;
this.nameNick = nameNick;
}
public String getNameLast() {
return nameLast;
}
public void setNameLast(String nameLast) {
this.nameLast = nameLast;
}
public String getNameFirst() {
return nameFirst;
}
public void setNameFirst(String nameFirst) {
this.nameFirst = nameFirst;
}
public String getNamePrefix() {
return namePrefix;
}
public void setNamePrefix(String namePrefix) {
this.namePrefix = namePrefix;
}
....
}
In Swift there is no access control (private/public) and the setter/getters are only for computed properties.
How should I implement this in swift?
Should I use a struct?
Perhaps I have to use willSet and didSet - I need your help ;)
You can make it really simple in Swift. There are many similar parts in Swift.
class Model : NSObject{
var nameFirst = ""
var nameSecond = ""
var nameLast = ""
init(nameFirst:String, nameSecond:String, nameLast:String){
self.nameFirst = nameFirst
self.nameSecond = nameSecond
self.nameLast = nameLast
}
}
Then, instead of using a get or a set method, you can simply use the variable to set and get the values of the variable:
var mod = Model(nameFirst: "hey", nameSecond: "what's", nameLast: "up")
println(mod.nameLast)
While didSet and willSet are useful for counting, how many times a method was set, you don't need it in this case. Also in your case you dont need to set get for these variables like that:
var value : Int {
get { return 10 }
}
Related
I've seen in polymer.dart they have:
class CustomTag {
final String tagName;
const CustomTag(this.tagName);
}
but how does that interact with the rest of the code? from just the code above I can't see how using #CustomTag('my-tag') actually does anything but creates a CustomTag which is then garbage collected since nothing is referencing it.
To answer the question in the title; these are called Annotations; they are simply const constructors.
To answer the second question; these are usually used for tooling (eg. #deprecated) or rewriting via a Transformer. You can access them at runtime using mirrors, but that's probably not practical/advisable for a production web app that gets converted to JavaScript.
Here's some sample code taken from this answer
import "dart:mirrors";
void main() {
var object = new Class1();
var classMirror = reflectClass(object.runtimeType);
// Retrieve 'HelloMetadata' for 'object'
HelloMetadata hello = getAnnotation(classMirror, HelloMetadata);
print("'HelloMetadata' for object: $hello");
// Retrieve 'Goodbye' for 'object.method'
var methodMirror = (reflect(object.method) as ClosureMirror).function;
Goodbye goodbye = getAnnotation(methodMirror, Goodbye);
print("'Goodbye' for object: $goodbye");
// Retrieve all 'Goodbye' for 'object.method'
List<Goodbye> goodbyes = getAnnotations(methodMirror, Goodbye);
print("'Goodbye's for object.method': $goodbyes");
// Retrieve all metadata for 'object.method'
List all = getAnnotations(methodMirror);
print("'Metadata for object.method': $all");
}
Object getAnnotation(DeclarationMirror declaration, Type annotation) {
for (var instance in declaration.metadata) {
if (instance.hasReflectee) {
var reflectee = instance.reflectee;
if (reflectee.runtimeType == annotation) {
return reflectee;
}
}
}
return null;
}
List getAnnotations(DeclarationMirror declaration, [Type annotation]) {
var result = [];
for (var instance in declaration.metadata) {
if (instance.hasReflectee) {
var reflectee = instance.reflectee;
if (annotation == null) {
result.add(reflectee);
} else if (reflectee.runtimeType == annotation) {
result.add(reflectee);
}
}
}
return result;
}
#HelloMetadata("Class1")
class Class1 {
#HelloMetadata("method")
#Goodbye("method")
#Goodbye("Class1")
void method() {
}
}
class HelloMetadata {
final String text;
const HelloMetadata(this.text);
String toString() => "Hello '$text'";
}
class Goodbye {
final String text;
const Goodbye(this.text);
String toString() => "Goodbye '$text'";
}
Output:
'HelloMetadata' for object: Hello 'Class1'
'Goodbye' for object: Goodbye 'method'
'Goodbye's for object.method': [Goodbye 'method', Goodbye 'Class1']
'Metadata for object.method': [Hello 'method', Goodbye 'method', Goodbye 'Class1']
Using Dart here.
As the above title suggests, I have a class (shown below) that has three bool instance variables. What I want to do is create a function that inspects the identifier names of these instance variables and prints each of them out in a string. The .declarations getter that comes with the ClassMirror class ALMOST does this, except it also gives me the name of the Constructor and any other methods I have in the class. This is no good. So really what I want is a way to filter by type (i.e., only give me the boolean identifiers as strings.) Any way to do this?
class BooleanHolder {
bool isMarried = false;
bool isBoard2 = false;
bool isBoard3 = false;
List<bool> boolCollection;
BooleanHolder() {
}
void boolsToStrings() {
ClassMirror cm = reflectClass(BooleanHolder);
Map<Symbol, DeclarationMirror> map = cm.declarations;
for (DeclarationMirror dm in map.values) {
print(MirrorSystem.getName(dm.simpleName));
}
}
}
OUTPUT IS:
isMarried
isBoard2
isBoard3
boolsToStrings
BooleanHolder
Sample code.
import "dart:mirrors";
void main() {
var type = reflectType(Foo);
var found = filter(type, [reflectType(bool), reflectType(int)]);
for(var element in found) {
var name = MirrorSystem.getName(element.simpleName);
print(name);
}
}
List<VariableMirror> filter(TypeMirror owner, List<TypeMirror> types) {
var result = new List<VariableMirror>();
if (owner is ClassMirror) {
for (var declaration in owner.declarations.values) {
if (declaration is VariableMirror) {
var declaredType = declaration.type;
for (var type in types) {
if (declaredType.isSubtypeOf(type)) {
result.add(declaration);
}
}
}
}
}
return result;
}
class Foo {
bool bool1 = true;
bool bool2;
int int1;
int int2;
String string1;
String string2;
}
Output:
bool1
bool2
int1
int2
using System;
using Android.App;
using Android.Os;
using Android.Widget;
using Dot42;
using Dot42.Manifest;
using Android.Location;
[assembly:UsesPermission(Android.Manifest.Permission.ACCESS_COARSE_LOCATION)]
[assembly:UsesPermission(Android.Manifest.Permission.INTERNET)]
[assembly:UsesPermission(Android.Manifest.Permission.ACCESS_FINE_LOCATION)]
[assembly: Application("simplegps")]
namespace simplegps
{
[Activity]
public class MainActivity : Activity
{
private LocationManager service;
private bool enable;
private string provider;
protected override void OnCreate(Bundle savedInstance)
{
base.OnCreate(savedInstance);
SetContentView(R.Layouts.MainLayout);
var txtprovider= FindViewById <TextView>(R.Ids.txtprovider);
var gpsstatus= FindViewById <TextView>(R.Ids.gpsstatus);
var txtcity = FindViewById<TextView>(R.Ids.txtcity);
var txtlat = FindViewById<TextView>(R.Ids.txtlat);
var txtlon = FindViewById<TextView>(R.Ids.txtlon);
service=(LocationManager)GetSystemService(LOCATION_SERVICE);
enable=service.IsProviderEnabled(LocationManager.GPS_PROVIDER);
if(enable)
{
gpsstatus.Text="Gps enabled";
}
else
{
gpsstatus.Text="Gps not enabled";
return;
}
var criteria = new Criteria{Accuracy = Criteria.ACCURACY_FINE};
provider = service.GetBestProvider(criteria,false);
var location = service.GetLastKnownLocation(provider);
if(location !=null)
{
txtprovider.Text=provider;
var latitude = location.Latitude;
var longitude = location.Longitude;
txtlat.Text=latitude.ToString();
txtlon.Text=longitude.ToString();
}
else
{
txtprovider.Text="no location";
return;
}
if(Geocoder.IsPresent())
{
Android.Location.Geocoder geo;
Android.Location.Address adds;
adds=geo.GetFromLocation(location.GetLatitude(),location.GetLongitude(),1);
}
}
}
}
error message:
It shows error "Cannot implicitly convert type 'Java.Util.IList' to 'Android.Location.Address'. An explicit conversion exists (are you missing a cast?) (CS0266)"
This is the line that fails:
adds = geo.GetFromLocation(location.GetLatitude(), location.GetLongitude(), 1)
geo.GetFromLocation returns Java.Util.IList<Address>. adds is of type Address. Hence the compile error.
Use the index operator to access one of the Addresses.
EDIT
Also, you should initialize geo before using it:
Geocoder geo = new Geocoder(this, Locale.getDefault());
Finally, GetFromLocation may return null or an empty list, so check for both.
Below is the code from the DotNetNuke Sample module that gets a collection of items from the database that belong to a particular module. What I want is add a second parameter for it filter by. I'm guessing this has something to do with modifying the scope item.cs class but am not sure how exactly.
public IEnumerable<Item> GetItems(int moduleId)
{
IEnumerable<Item> t;
using (IDataContext ctx = DataContext.Instance())
{
var rep = ctx.GetRepository<Item>();
t = rep.Get(moduleId);
}
return t;
}
Any ideas?
Another way to do it in DAL2 is using the .Find() method. This is good if you want to query on an indexed field in your table and you don't care about caching scope:
public IEnumerable<Item> GetItemByName(int moduleId, string itemname)
{
IEnumerable<Item> t;
using (IDataContext ctx = DataContext.Instance())
{
var rep = ctx.GetRepository<Item>();
t = rep.Find("WHERE ModuleId = #0 AND ItemName LIKE #1", moduleId, itemname);
}
return t;
}
Here's some sample code from my SignalRChat module that uses DAL2 (http://signalrchat.codeplex.com/SourceControl/changeset/view/71473#1272188)
public IEnumerable<Message> GetRecentMessages(int moduleId, int hoursBackInTime, int maxRecords)
{
var messages = (from a in this.GetMessages(moduleId) where a.MessageDate.Subtract(DateTime.UtcNow).TotalHours <= hoursBackInTime select a).Take(maxRecords).Reverse();
return messages.Any() ? messages : null;
}
That is one approach, you can also use a SQL statement within the controller as well (http://signalrchat.codeplex.com/SourceControl/changeset/view/71473#1272186)
public ConnectionRecord GetConnectionRecordByConnectionId(string connectionId)
{
ConnectionRecord t;
using (IDataContext ctx = DataContext.Instance())
{
var connections = ctx.ExecuteQuery<ConnectionRecord>(CommandType.Text,
string.Format(
"select top 1 * from {0}{1}SignalRChat_ConnectionRecords where ConnectionId = '{2}'",
_databaseOwner,
_objectQualifier,
connectionId)).ToList();
if (connections.Any())
{
t = connections[0];
}
else
return null;
}
return t;
}
i'm using as2. How do i delete these snowfalkes on a certain frame? i'm creating the snowlfakes using an array on frame 40. I want to get rid of the frames around 60.
var snowflake:Array;
for (var i:Number=0;i<100;i++) {
snowflake[i]=new Snowflake(this);
}
import Snowflake.*;
class Snowflake {
public var _snowflake:MovieClip;
private var _ranSnowflake:Number;
private var i:Number;
private var k:Number;
private var rad:Number;
private static var NUM_SNOWFLAKE_TYPES:Number=7;
private static var MOVIE_WIDTH:Number=590;
private static var MOVIE_HEIGHT:Number=390;
private static var FALLING_SPEED:Number=30;
private static var WIND_SPEED:Number=5;
private static var ROTATION_SPEED:Number=4;
function Snowflake(container:MovieClip) {
this._ranSnowflake=Math.round((Math.random()*Snowflake.NUM_SNOWFLAKE_TYPES)+1);
this._snowflake=container.attachMovie("snowflake"+this._ranSnowflake,"snowflake",container.getNextHighestDepth());
this._snowflake._x=(Math.random()*Snowflake.MOVIE_WIDTH);
this._snowflake._y=0;
this._snowflake.parent=this;
this.i=1+Math.random()*2;
this.k=-Math.PI+Math.random()*Math.PI;
this.rad=0;
//giving each snowflake unique characteristics
this._snowflake._xscale = this._snowflake._yscale=Math.random()*30;
this._snowflake._alpha = 75+Math.random()*100;
this._snowflake.onEnterFrame=function() {this.parent.snowflakeEnterFrame(this._snowflake);}
trace("SNOWFLAKE X:"+this._snowflake._x+" Y:"+this._snowflake._y);
trace(this._currentframe);
}
public function snowflakeEnterFrame() {
//putting it all together
this.rad += (k/180)*Math.PI;
this._snowflake._x -= Math.cos(rad);
this._snowflake._y += i;
if (this._snowflake._y>=Snowflake.MOVIE_HEIGHT) {
this._snowflake._y = -Snowflake.FALLING_SPEED;
}
if ((this._snowflake._x>=Snowflake.MOVIE_WIDTH) || (this._snowflake._x<=0)) {
this._snowflake._x = -Snowflake.WIND_SPEED+Math.random()*Snowflake.MOVIE_WIDTH;
this._snowflake._y = -Snowflake.WIND_SPEED;
}
this._snowflake._rotation+=Snowflake.ROTATION_SPEED;
}
public function vis(){
this._snowflake.visible = false;
}
}
Something like this (should work on any frame):
for(var i:Number = 0; i<snowflake.length; i++){
this.removeMovieClip(snowflake[i]._snowflake);
}
Loop through all the snowflake and remove them from the container.