If you have the following function, for example:
public Tuple<int, int> GetMultipleValue()
{
return Tuple.Create(1,2);
}
How would you access those integers in your main program, after calling GetMultipleValue()?
Tuple classes have properties with very "logical" names: Item1, Item2, Item3, ...
Tuple<int, int> temp = GetMultipleValue();
Console.WriteLine("{0}; {1};", temp.Item1.ToString(), temp.Item2.ToString());
From MSDN Tuple <T1, T2> Class
My understanding is that you would save your return value into a tuple object. For example
var myTuple = GetMultipleValue()
And then you can access the individual parts of the tuple by
myTuple.Item1
or
myTuple.Item2
Related
I am trying to create a dictionary from an array of struct using grouping but I am not having much luck (I found a way iterating over every record but was hoping for a more elegant solution)...
var eventRecords = [EventRecord]()
and the structure looks like this (used to store records in CloudKit)
public struct EventRecord {
public var evDate: Date
public var evType: Int
public var evMainTxt: String
public var evNote: String?
public var evVal1: Int?
public var evVal2: Int?
}
what I am hoping to accomplish is a dictionary where the key is evType and the value is [evMainTxt]. the dict is defined as
var suggestionsDict = [Int: [String]]()
I started with Dictionary(grouping: eventRecords, by: {$0.evType}) but I am strugling with the .map portion of this statement Dictionary(grouping: eventRecords, by: {$0.evType}).map since I only want a subset of the EventRecord struct. Can it be done short of iterating over all the records? Since I am new to this, any advice will be appreciated.
The easiest way to do this is to use reduce(into:) so you can map and group in one step
let suggestionsDict = eventRecords.reduce(into: [:]) {
$0[$1.evType, default: []].append($1.evMainTxt)
}
I have this method
private fun checkRoomIdAndFindCinemaAndCheckIfRoomExists(paramRoomId: String?, paramCinemaId: String?, roomExists: Boolean?) : Array<Any> {
val roomId = ValidationHandler.validateId(paramRoomId, "room id")
val cinema = cinemaService.getCinemaById(paramCinemaId)
val roomExists = roomRepository.existsByIdAndCinemaId(roomId, paramCinemaId!!.toLong())
return arrayOf(roomId, cinema, roomExists)
}
What i want to do here is add roomId as Long , cinema as object and roomExists as boolean into an array, and return type should be the array. How can i do that?
Later i want to access these from another method.
I suggest to use idiomatic Kotlin code instead of what was suggested already. When you want to return multiple values from a function, you should utilize data functions or existing classes like Pair or Triple if sufficient. In this case, Triple helps you:
private fun checkRoomIdAndFindCinemaAndCheckIfRoomExists(
paramRoomId: String?,
paramCinemaId: String?,
roomExists: Boolean?
): Triple<Long, Any, Boolean.Companion> {
//TODO
return Triple(roomId, cinema, roomExists)
}
The good thing is that you can be sure about the types and don't have to cast anything from an unsafe Array<Any>. Furthermore, data classes let you make use of destructuring as shown here:
val (roomId, cinema, roomExists) =
checkRoomIdAndFindCinemaAndCheckIfRoomExists("id1", "id2", true)
You can call the method like this:
val array = checkRoomIdAndFindCinemaAndCheckIfRoomExists(paramRoomId, paramCinemaId, roomExists)
The array's inferred type is Array<Any>.
You can access the items of the array:
val roomId = array[0] as Long
val cinema = array[1] as YourObjectClass
val roomExists = array[2] as Boolean
I have an array of Tag objects that have a property called tag, which is a string.
public struct Tag {
public let name: String
}
I would like to get an array of all of these name properties.
Given an array of tags, in Objective-C I would accomplish this with this line:
NSArray *tagNames = [tags valueForKey:#"name"]
How can I achieve the same thing in Swift?
I've tried:
let tagNames = tags.map({ $0.name })
But get a compiler error: "Value of type '[Tag]' has no member 'name'.
It looks like you have an array which contains another array of Tag objects.
This works for me:
let tags = [Tag(name: "tag1"), Tag(name: "tag2"), Tag(name: "tag3")]
let names = tags.map{$0.name }
print("Names: \(names)")
Goal: I have two different classes, and two arrays containing members of each class. Using Swift 2.0, I would like to find the unique members of one array compared to the other based on specific attributes of each class.
Example:
class A {
var name: String
init(name: String) {
self.name = name
}
}
class B {
var title: String
init(title: String) {
self.title = title
}
}
let aArray = [A(name:"1"), A(name:"2"), A(name:"3"), A(name:"4")]
let bArray = [B(title:"1"), B(title:"2"), B(title:"5")]
So, I'm looking for some operation between aArray and bArray which returns the 3rd and 4th element of aArray, because they are uniquely in aArray, where the basis of comparison is the attributes A.name and B.title.
Of course, reversing the order of the operation would pick out the 3rd element of bArray, because it is uniquely in bArray.
I know I can accomplish the goal straightforwardly using a simple for loop, but I was hoping for something more elegant and more optimized. But if a for loop is as fast or faster than anything fancier, I'm happy to use it just as well.
I'm not sure fancy or elegant this code is, but, we could do something like this:
let mappedArray = bArray.map { $0.title }
let filteredArray = aArray.filter { !mappedArray.contains($0.name) }
So when we want the unique elements from aArray, we first map the elements from bArray to get an array of the value we want to actually compare:
let mappedArray = bArray.map { $0.title }
mappedArray is just an array of strings based on the title property of the objects in bArray.
Next, we use the filter method to filter objects from aArray. The filter method returns an array with objects that pass the test in our closure. The test we want to apply is objects that are not contained in the mapped array we just built.
let filteredArray = aArray.filter { !mappedArray.contains($0.name) }
If we want to do it the other way, just change a few things:
let mappedArray = aArray.map { $0.name }
let filteredArray = bArray.filter { !mappedArray.contains($0.title) }
Using GAE-Java-JDO, is it possible to filter on the value of a specific element in a list?
WHAT WORKS
Normally, I would have the following:
#PersistenceCapable
class A {
String field1;
String field2;
// id, getters and setters
}
Then I would build a simple query:
Query q = pm.newQuery(A.class, "field1 == val");
q.declareParameters("String val");
List<A> list = new ArrayList<A>((List<A>) q.execute("foo"));
WHAT I WOULD LIKE
The above works fine. But what I would like to have is all of the fields stored in a list:
#PersistenceCapable
class AA {
ArrayList<String> fields;
// id, getters and setters
}
and then be able to query on a specific field in the list:
int index = 0;
Query q = pm.newQuery(A.class, "fields.get(index) == val");
q.declareParameters("int index, String val");
List<A> list = new ArrayList<A>((List<A>) q.execute(index, "foo"));
But this throws an exception:
org.datanucleus.store.appengine.query.DatastoreQuery$UnsupportedDatastoreFeatureException:
Problem with query
<SELECT FROM xxx.AA WHERE fields.get(index) == val PARAMETERS int index, String val,>:
Unsupported method <get> while parsing expression:
InvokeExpression{[PrimaryExpression{strings}].get(ParameterExpression{ui})}
My impression from reading the GAE-JDO doc is that this is not possible:
"The property value must be supplied by the application; it cannot refer to or be calculated in terms of other properties"
So... any ideas?
Thanks in advance!
If you only need to filter by index+value, then I think prefixing the actual list-values with their index should work. (If you need to also filter by actual values, then you'll need to store both lists.)
i.e. instead of the equivalent of
fields= ['foo', 'bar', 'baz] with query-filter fields[1] == 'bar'
you'd have
fields= ['0-foo', '1-bar', '2-baz'] with query-filter fields == '1-bar'
(but in java)