how can I return a result from a function into a variable? - swift

I have a variable :
var name = [Nick,John,Peter]
and a function:
func name(){
var personname = []
.......
return personname
}
the result of the function are the names of the people Nick,John,Peter. How can I return the result into the variable.I mean I do not want to write the names manually I want to populate them from the function, because the function display all of the names. I am beginner and I will be glad if you show me the right syntaxis.
var name = [????] = [personname()] or how????

You should use -> to return something from a function. Here is an example:
static let people = ["Nick", "John", "Peter"]
func getPerson(index: Int) -> String
{
return self.people[index] //index is number of a person, 0 will be the first one, 1 is second, etc.
}
func showTeam()
{
// some code
print("This is a first boy: \(self.getPerson[0])")
// some code
}

Related

How to put a variable in a for loop with different end number

I’ve got multiple variables with the same name but a different number on the end like this:
MyVar1, MyVar2, MyVar3, MyVar4
and they are either true or false
How do I write this correctly?
For index in Range(1...4){
if (“MyVar” + index) == true{
print(“:)”)
}
}
didnt tries the solution but according to this post: https://stackoverflow.com/a/45622489/5464805 you can do this:
Edit: I read that your variables are Booleans
for i in 0...4 {
if let var = myObject.value(forKey: "MyVar\(i)") as Bool,
var { // If var is successfully cast and true it enters the statement
print(var)
}
}
HOWEVER
All the other solutions above or below are still correct. This is something you dont usually do in Swift in general unless you must do so.
You should either rewrite your model and give a proper name to each variables, that you will later put into an array such as...
class MyObject {
var MyVar1: Bool // To Rename
var MyVar2: Bool // To Rename
var MyVar3: Bool // To Rename
var MyVars: [Bool] {
get { return [MyVar1, MyVar2, MyVar3] }
}
}
Or you completely get rid of these variable and create an Array directly
class MyObject {
// var MyVar1: Bool // To Delete
// var MyVar2: Bool // To Delete
// var MyVar3: Bool // To Delete
var MyVars: [Bool]
}
and you set the Array / Dictionnary in accordance to your needs
You are trying to get a sum of String ("MyVar") and Int ("index") and compare that sum with Bool (true)
It would be more safety to store all your variables in an array like that
let myVars = [MyVar1, MyVar2, MyVar3, MyVar4]
Then you can iterate throught the array:
for i in myVars {
if i {
print(i)
}
}
You can't create a variable from concatenation at runtime , you need to have an array of bool like this
var arr = [false,true,true,false] // var1 , var2 , var3 , var4
for item in arr {
if item {
}
}

Mark closure element mutable Swift

I have 2 structs, first is:
struct LineData {
init (name: String,
colorValue: String,
values: [Int]){
self.name = name
self.colorValue = colorValue
self.values = values
}
private var cachedMaxValue: Int? = nil
let name: String
let colorValue: String
let values: [Int]
// describe max value for Y axis for specific Line
mutating func maxValue() -> Int{
if let cached = cachedMaxValue {
return cached
}
self.cachedMaxValue = values.max()
return cachedMaxValue ?? 0
}
}
Second have array of LineData structs:
struct CharData {
init(xAxis: XAxis,
lines: [LineData]){
self.xAxis = xAxis
self.lines = lines
}
private var cachedMaxValue: Int? = nil
var xAxis: XAxis
var lines: [LineData]
// describe max value for Y axis among lines
func maxValue() -> Int{
var maxValues: [Int] = []
lines.forEach{it in
maxValues.append(it.maxValue())
}
return 0
}
}
Code above not compile, because, of error on method maxValues for struct CharData. It says Cannot use mutating member on immutable value: 'it' is a 'let' constant
What i want is, iterate through an array of lines and among it max values find greater value.
Since lines is an ordinary array, how about simply:
for i in 0..<lines.count {
maxValues.append(lines[i].maxValue())
}
perhaps not quite as Swifty, but nothing gets copied. The optimizer ought to give you pretty much the same performance as forEach.
It's the it parameter/object in the forEach that's immutable. Just like the error says: "it is a let". You could probably do something like this:
lines.forEach { it in
var mutableIt = it
maxValues.append(mutableIt.maxValue())
}
It should be noted that this will create a mutable copy of the "it" struct instance.

How to collect the return value of a function (Swift 3)

Goal:
I want to collect the return value of a function.
Question:
How can I call the 'test' function to collect the return variable 'name' without passing through a parameter?
Is there a way to collect a variable(values) from functions with agruments(parameters) without passing through a parameter?
I have provided an example:
let userName = "Jake"
let userInfo = test(name: userName)
func test(name: String) -> String {
return name
}
// function call
// Goal: I want to retrieve the function return value without passing a parameter
let newUser = test()
Does the function 'test' return value have to be stored to retrieve it?
I want to retrieve the 'userName' Jake
You can return like below,
let userName = "Jake" //Global variable of the class
let userInfo = test() //Jake
func test() -> String { //single - element tuple will don't have label for return.
return self.userName
}
If you like to return with labels then you need tow or more return values like below,
func test() -> (name:String,age:Int) {
return (self.userName,125)
}
And access specific values by test().name

How to use BFTask with Swift and AWS DynamoDB?

I'm using DynamoDb with swift to make an iPhone application.
I'm trying to query a table I have in my database and then use that queried data to load(query) a different table with the data received.
I'm querying a friends table and then querying a books table. To do this I have a function called queryFriends and queryBooks, which looks like this:
//these are mapper classes for DynamoDB
func queryFriendsTable(hash: Int) -> BFTask! {
let mapper = AWSDynamoDBObjectMapper.defaultDynamoDBObjectMapper()
var item = Friends()
item.UserId = 0
item.friendId = 0
let task1 = mapper.save(item)
let exp = AWSDynamoDBQueryExpression()
exp.hashKeyValues = hash
return mapper.query(Friends.self, expression: exp)
}
func loadBooksTable(hash: Int) -> BFTask! {
let mapper = AWSDynamoDBObjectMapper.defaultDynamoDBObjectMapper()
var item = Books()
item.UserId = 0
item.name = ""
item.bookId = 0
item.author = ""
let task1 = mapper.save(item)
return mapper.load(Books.self, hashKey: hash, rangeKey: nil)
}
I then call these functions in the viewDidLoad section. I use the queryFriendsTable() with a BFTask to call the first query on the friends table and then put the loadBooksTable() inside that function call with another BFTask call.
Here is the code:
//the function is called and takes in "1" as a parameter to query the table with.
self.queryFriendsTable(1).continueWithSuccessBlock{(task: BFTask!) -> BFTask! in
let results = task.result as! AWSDynamoDBPaginatedOutput
for r in results.items {
//this loads the books table and takes the friendId's gotten as an argument
self.loadBooksTable(r.friendId).continueWithSuccessBlock{ (task: BFTask!) -> BFTask! in
let books = task.result as! Books
//this is just a label on the screen to test what I'm doing
self.testLabel.text = books.name
return nil
}
}
return nil
}
This works but it takes about 15 seconds for the label to be replaced by the name. I know its not taking that long to get the data though because if I were to do just println(books.name) it takes less then a second to print the name.
So I'm wondering why its taking so long. I tried to google it but I couldn't figure it out. I figure it has something to do with the BFTasks inside eachother but I'm not sure.
Any help is appreciated. Thanks!

Strange function-like property – can someone explain this piece of Swift code?

I found this piece of code regarding sections in a table view in order to make an index in a table view:
class User: NSObject {
let namex: String
var section: Int?
init(name: String) {
self.namex = name
}
}
// custom type to represent table sections
class Section {
var users: [User] = []
func addUser(user: User) {
self.users.append(user)
}
}
// raw user data
let names = [
"Clementine",
"Bessie",
"Annis",
"Charlena"
]
// `UIKit` convenience class for sectioning a table
let collation = UILocalizedIndexedCollation.currentCollation() as UILocalizedIndexedCollation
// table sections
var sections: [Section] {
// return if already initialized
if self._sections != nil {
return self._sections!
}
// create users from the name list
var users: [User] = names.map { namess in
var user = User(name: namess)
user.section = self.collation.sectionForObject(user, collationStringSelector: "namex")
return user
}
// create empty sections
var sections = [Section]()
for i in 0..<self.collation.sectionIndexTitles.count {
sections.append(Section())
}
// put each user in a section
for user in users {
sections[user.section!].addUser(user)
}
// sort each section
for section in sections {
section.users = self.collation.sortedArrayFromArray(section.users, collationStringSelector: "namex") as [User]
}
self._sections = sections
return self._sections!
}
var _sections: [Section]?
The part that I didn't understand is this:
// table sections
var sections: [Section] {
// return if already initialized
if self._sections != nil {
return self._sections!
}
// etc...
return self._sections!
}
var _sections: [Section]?
My questions are:
What does that mean var sections: [Section] { }? I guess it's not a function as there is no func keyword in front.
What is this var _sections: [Section]? What's the reason to place an _ in front?
It is very similar to a function despite the absence of keywords – it’s a computed property.
These look like variables, but act like functions. They can be read-only (get but not set), or can have both a get and a set version. Here’s a simpler example:
var y = 3
var x: Int {
get { return 2*y }
}
println(x) // prints 6
y += 1
println(x) // prints 8
var z: Int {
get { return y }
set(newVal) { y = newVal }
}
println(z) // prints 4
z = 10 // sets y to 10
println(x) // prints 20 (2*10)
When it’s only a get, you can omit the keyword, which is how it’s being done in the version in your question. The declaration of x above could have been written without it:
var x: Int {
return 2*y
}
The var _sections in your example is playing a similar role to the y variable in the above code – it’s the underlying data from which the computed property result is derived. The reason for the _ is just to indicate that it is a internal implementation detail. The underscore’s not meaningful to Swift itself, that’s just a naming convention people use.
It's a read-only computed property. They act like properties, but are computed each time. You can read more about it in the docs. Check out the section on "Computed Properties" as well as the "Read-Only Computed Properties" section to understand the shorthand.