I create object and dao class for work with sql
object UserTable : IdTable<Int>("User") {
val parameters = reference("search_parameters_id", SearchParametersTable)
override val id = integer("id").entityId()
override val primaryKey = PrimaryKey(id)
}
class User(id: EntityID<Int>) : Entity<Int>(id) {
companion object : EntityClass<Int, User>(UserTable)
var searchParameters by SearchParameters referencedOn UserTable.parameters
}
But I cann't set id, beacause id is val
Do you mean that you want to insert a record with an arbitrary id
value? If yes, you can write like below.
val newId = 10
User.new(newId) {
// set values to other columns
}
Related
How can I auto add a new class instance to an array?
Example:
class Product {
var name: String?
}
var products = [Product]()
How can I add a new instance of a Product class to the products Array? How can I append to the array?
I tried some code but I don't know how to reference the class in own class.
I tried something like this:
class Product {
var name: String?
init() {
products.append(Produt)
}
var products = [Product]()
Thanks!
If you want your newly created object stored in products array then you need to declare it as static property so that it is shared by all instance otherwise it will just add first object for your every instance.
class Product {
var name: String?
static var products = [Product]()
init() {
Product.products.append(self)
}
init(name: String) {
self.name = name
Product.products.append(self)
}
}
Now use this products array using Product.products.
_ = Product(name: "One")
_ = Product(name: "two")
print(Product.products)
I dont't know why you need it, but you can use
class Product {
static var products: [Product] = []
var name: String?
init() {
products.append(self)
}
}
Have you tried products.append(self) ?
Scene, I've an array of NSObject class named Comment like var comments:[Comment]?. This class has property commentBywhich is also a NSObject class named User and it has property to identify unique user which is var key:String.above description as code,
class Comment:NSObject {
var commentBy:User?
}
class User:NSObject {
var key:String?
}
//In some other class
class someClass {
var comments:[Comment]?
}
What I want
I want an unique array of Comment, suppose that userA has made 2 comments and userB has made 1 comment so there is three comments total, but in my unique array, I want to show that two users made comments.
what should I do?
var comments: [Comment]?
let userKeys = comments?.flatMap { $0.commentBy?.key } ?? []
let set = Set(userKeys)
If all you want is the total number of unique user that have commented, then I think mapping comments to user's key then create a set of key is faster.
See what i do, actually your question is How to init a NSSet in swift ?
class Comment:NSObject {
var commentBy:User?
}
class User:NSObject {
var key:String?
}
//In some other class
class someClass {
var comments:[Comment]?
}
let user1 = User()
user1.key = "1"
let user2 = User()
user1.key = "2"
let c1 = Comment()
c1.commentBy = user1
let c2 = Comment()
c2.commentBy = user1
let c3 = Comment()
c3.commentBy = user2
let set: NSSet = [user1, user2]
let set2: NSSet = [user2]
set2.isSubset(of: set as! Set<AnyHashable>) //true
let set3: NSSet = [c1, c1]
set3.count //1
let set4: NSSet = [c1, c2, c3] // your unique array
let set5 = NSSet(array: [c1, c2, c1, c3])
set5.count //3
set3 will always be [c1], because the elements in Set or NSSet will be unique.
First make User hashable in a way that makes them equal based on their unique key.
class User: NSObject
{
let key:String
init(key: String) { self.key = key }
override func isEqual(_ object: Any?) -> Bool
{
guard let other = object as? User else { return false }
return self.key == other.key
}
override var hashValue: Int { return key.hashValue }
}
let eq = User(key: "foo") == User(key: "foo") // true
let h1 = User(key: "foo").hashValue // some big number
let h2 = User(key: "foo").hashValue // same big number as above
I've made key immutable because, as it serves to uniquely identify a user, it should not be possible to change.
Because User is an NSObject it already has an implementation of == which uses isEqual: so you override that to compare based on the key. You also use the hashValue of key as the User hash value.
Now you can use User in sets and as keys in dictionaries. If you do the same for Comment so that they compare equal on User you can use comments in a set too. However, that is a bad idea. Two comments are not the same just because they have the same user. You should change SomeClass to use a dictionary keyed by user as follows:
class Comment: NSObject
{
let user: User
let text: String
init(user: User, text: String)
{
self.user = user
self.text = text
}
}
class SomeClass
{
var userComments: [User : [Comment]] = [:]
func addComment(newComment: Comment)
{
if let existingComments = userComments[newComment.user]
{
userComments[newComment.user] = existingComments + [newComment]
}
else
{
userComments[newComment.user] = [newComment]
}
}
var userCount: Int { return userComments.count }
var commentCount: Int { return userComments.values.reduce(0, { $0 + $1.count}) }
}
The property userCount is the number you asked for. The property commentCount is the total number of comments - although beware: the implementation runs in O(n) time. If speed is of the essence, you should maintain a counter that increments each time you add a comment.
trying to filter an array of custom object type ParseEmployee which inherits from NSObject.
Any ideas what could be causing this error?
Consider the following example:
struct MyEmployee {
var employeeId : Int
var employeeName : String
var employeeAge : Int
var employeeGender : String
init(_ id: Int, _ name: String, _ age: Int, _ gender: String) {
employeeId = id
employeeName = name
employeeAge = age
employeeGender = gender
}
}
var arrayOfEmployees : [MyEmployee] = [MyEmployee(1, "John", 28, "Male"), MyEmployee(2, "Sarah", 35, "Female"), MyEmployee(3, "Christine", 24, "Female")]
var filtered = arrayOfEmployees.filter {employee in employee.employeeAge < 30 }
print(filtered) // Employee objects John and Christine
The closure following .filter suffix to your array must be of return type Bool ("element-type-of-array" -> Bool). You either explicitly add a return or simply make sure the statement following employee in is one that evaluates to type Bool (e.g., employee.employeeAge < 30, which returns true or false).
Note that you can treat the closure as any anonymous closure type, not necessarily using a single-line statement. E.g.:
var anotherFiltered = arrayOfEmployees.filter{
employee in
return employee.employeeAge < 30 && employee.employeeGender == "Female" }
print(anotherFiltered) // Employee object Christine
You should be able to run as the following:
filtered = arrayOfEmployees.filter { // filter them here }
$0 will be the member of the array and you just have to make sure the braces return a true or false Bool, you do not need to do (employee) -> Bool in here.
If you wanted employee just do the following:
filtered = arrayOfEmployees.filter { employee in // filter here }
Your filter closure has to return a Bool.
So something like.
filtered = arrayOfEmployees.filter { return true }
Now that's not useful because nothing is filtered but it fixes your error. Let's say your ParseEmployee has a property isManager:Bool. Then you could do something like.
filtered = arrayOfEmployees.filter { $0.isManager }
My problem was that I had copied and pasted the "filtered" array from another class and didn't change it to the appropriate class type that was being filtered. I changed the filtered array to the correct class and this resolved the error.
There are many good examples of searching multiple string values in LINQ e.g.
public static Product[] GetProducts(Guid[] prodIDs)
{
return (from p in GetProducts()
where prodIDs.Contains(p.ProductID)
select p).ToArray<Product>();
}
I have a list of Products that I need to match from a customer,
but I dont have an exact match - the Customers List Of Products contains my ProductID - but it is not exact - e.g.
Customer MyCompany
Description Description
Prod1XY Prod1
AProd2B Prod2
XXXProd3 Prod3
I thus cannot filter from the prodIDs [string array] because Prod1 does not contain Prod1XY
and thus cannot use the examples that are available.
How can I effectively change (reverse) the working examples
as to search CustomerProducts where it contains my Product Description please?
So to confirm : this is not a duplicate. The examples use the string[] x
input parameter and then searches:
where x.contains
I need help to get it : myProducts.Contains(x)
another online example modified to show the situation:
static void Main(string[] args) {
var table = new[] {
new { uid = 1 },
new { uid = 2 },
new { uid = 3 },
new { uid = 4 },
new { uid = 5 }
};
var stringarray = new[] { "1", "5", "10" };
var results = from xx in table
where table.Contains(stringarray)
select xx;
foreach (var result in results) {
Console.WriteLine("Result: " + result.uid.ToString());
}
}
It is not clear enough what you are trying to accomplish, but under assumption that you want to select all products where ProductID contains any value from specified list, it looks like that it:
public static Product[] GetProducts(string[] prodIDs)
{
return (from p in GetProducts()
where prodIDs.Any(id=>p.ProductID.Contains(id))
select p).ToArray<Product>();
}
Try this
public static Product[] GetProducts(string[] prodIDs)
{
return (
from p in GetProducts()
from q in prodIDs
where p.ProductID.IndexOf(q) > -1
select p)
.ToArray<Product>();
}
I have a collection of these Javascript objects: (Displayed as a DTO)
public class ParameterValueDTO : DataTransferObject
{
public int Id { get; set; }
public String Comments { get; set; }
public String Description { get; set; }
}
By default, AngularJS UI-Grid will create a row for each ParameterValue object with 3 columns: Id, Comments, Description which works fine.
IMAGE: Standard objects mapping to table
What I would like to do however is create a column for each object's "Comments" value and bind it to the corresponding "Description" value. Essentially pivoting the table so it only has 1 row (forget the ID column for now).
The javascript I've tried:
var cols = [];
var row = obj.data.ProductAttributes[0].Specifications[0].ParameterValues
var length = row.length;
for (var i = 0; i < length; i++) {
cols.push({
field: "Description",
displayName: row[i].Comments
});
}
$scope.gridOptions = {
columnDefs: cols,
data: row
};
The above results in the following which is obviously wrong:
IMAGE: One column, new row for each Description
Is it possible to accomplish this with the current data structure or what exactly is the correct approach I should be taking?
I'd modify the code to just reprocess your data. ui-grid really only likes to bind to columns and rows, it can't reverse the order.
So you'd:
var pivotData = [ {} ];
data.forEach(function(parameterDTO) {
pivotData[0][parameterDTO.comments] = parameterDTO.description;
});
Then you should be able to use that new data object as grid data.