Swift Get value from function - swift

I have two class and i would like to get a variable with the value (the variable is in a function) to my second class :
public class StreamPlayer {
class var sharedInstance : StreamPlayer{
struct Static {
static let instance : StreamPlayer = StreamPlayer()
}
return Static.instance
}
public var intermediate = NSString()
func metaDataUpdated(metaData : NSString){
var result : String = ""
var listItems = metaData.componentsSeparatedByString(";") as [String]
if (listItems.count > 0){
var containerName = listItems[0]
result = "StreamTitle=\'([^\"]*)\'".matchesForRegexIn(containerName, atRangeIndex: 1)
self.intermediate = result
}
}
}
and the second class
class RadioViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
println(test + StreamPlayer.sharedInstance.intermediate)
}
}
The problem is that the var intermediate doesn't change and don't get the value of result (in my first class)

I've copied your StreamPlayer class code into a playground. I've just commented out the matchesForRegexIn method as it seems it's your String extension so my code looks like this:
public class StreamPlayer {
class var sharedInstance : StreamPlayer{
struct Static {
static let instance : StreamPlayer = StreamPlayer()
}
return Static.instance
}
public var intermediate = String()
func metaDataUpdated(metaData : NSString){
var result : String = ""
let listItems = metaData.componentsSeparatedByString(";") as [String]
if (listItems.count > 0){
// var containerName = listItems[0]
result = "StreamTitle=\'([^\"]*)\'" //.matchesForRegexIn(containerName, atRangeIndex: 1)
intermediate = result
}
}
}
// calling the method to make sure intermediate gets updated
StreamPlayer.sharedInstance.metaDataUpdated("asd")
// check if it got updated
print(StreamPlayer.sharedInstance.intermediate)
The last line prints StreamTitle=\'([^\"])\'* so all is good. Just make sure to call StreamPlayer.sharedInstance.metaDataUpdated before checking intermediate
PS. I'm really not sure what you're trying to achieve by sharing intermediate results from a function to the outside world but it feels off. Think about splitting metaDataUpdated method into two methods maybe?
PPS. metaDataUpdated is a really bad name for a function
PPPS. If I were you I'd declare intermediate as String?

self.intermediate is a NSString while result is a String
Try
self.intermediate = result as NSString

Related

Why Instance member 'getPerson' cannot be used on type 'GetPerson'

I write code in a Cocoa framework and call the function in it from main project. But it fails always returning a message. I fix this in two ways.
First, in main project viewController:
import getPerson
override func viewDidLoad() {
super.viewDidLoad()
var person = GetPersons.getPerson(name: "Jack")
}
Returns:
Instance member 'getPerson' cannot be used on type 'GetPerson'; did you mean to use a value of this type instead
Second:
import getPerson
override func viewDidLoad() {
super.viewDidLoad()
let vc = GetPersons.self
var person = vc.getPerson(name: "Jack")
}
Returns:
Instance member 'getPerson' cannot be used on type 'GetPersons'
What's happening with this? How do I fix it?
In test framework :
import Fundation
public class GetPersons {
public struct Person {
public var name : String = ""
public var age : Int = 0
}
public func getPerson(name : String) -> Person {
var person = Person()
return person
}
}
In your first example, it's telling you that you defined getPerson(name: String) as an instance method. (Presumably because it operates on instance properties.)
You are calling it here as if it were defined as:
static func getPerson(name: String) { ...
The second is saying much the same thing, without guessing what you want to do.
If I understand what you want to do, I think it goes something like this:
class GetPersons {
struct Person {
public var name : String = ""
public var age : Int = 0
}
func getPerson(name : String) -> Person {
var person = Person()
return person
}
}
Then, in your view controller define a property for the instance of GetPersons:
let gp = GetPersons()
then in viewDidLoad:
let person = gp.getPerson(name: "Jack")
Also, is GetPersons in an actual framework, or is it simply a class defined (as it should be) in a separate file?

Swift - Declare Struct in two different files

I just approached Swift and I'm encountering some problems...
I have a class which helps me to fetch some results
class ExpencesOperations {
struct ExpencesByDate {
var day: String!
var expence: [PFObject]
}
var expencesByDateArray = [ExpencesByDate]()
func getExpencesByDate(expences: [PFObject]) -> [ExpencesByDate] {
..... my function
return expencesByDateArray
}
}
When I call it in my TableViewController I don't know how to redeclare the struct ExpencesDate!
class HomeTableViewController: UITableViewController {
var myCurrency = MyCurrency()
var expencesOperations = ExpencesOperations()
var expencesByDateArray = [ExpencesOperations.ExpencesByDate]() /* Not Working */
func fetchExpences() {
expencesByDateArray = self.expencesOperations.getExpencesByDate(someInput) /* here i get the error */
}
Put the struct outside of your class scope and it should be visible to other files as well.
struct ExpencesByDate {
var day: String!
var expence: [PFObject]
}
class ExpencesOperations {
var expencesByDateArray = [ExpencesByDate]()
func getExpencesByDate(expences: [PFObject]) -> [ExpencesByDate] {
..... my function
return expencesByDateArray
}
}
You need to provide arguments for proper initialization of the ExpencesByDate struct (I think you meant ExpenSes, right?)
For example:
var expencesByDateArray = [ExpencesOperations.ExpencesByDate(day: "Friday", expence: [PFObject]())]
And regarding:
...getExpencesByDate(someInput) /* here i get the error */
The function you created expects an array:
func getExpencesByDate(expences: [PFObject]) -> [ExpencesByDate]
It's not clear from your question what someInput is. Is that an array?
As you posted in the question, it will always fail.
Plus, what are the compiler error messages?

Swift - A function with no parameters with return value

I am learning Swift and am writing a basic card game init function where I want to use a function to setup some decks.
Swift keeps complaining that I'm missing an argument in parameter #1, but there aren't any parameters, nor am I wanting any.
Game class is as follows
class Game
{
// MARK: ** Private vars **
private var gameState: GameState?
private var playerOnTurn: Player?
private var seedCash:Int?
// MARK: ** Public vars **
lazy var players = [Player]()
var chequesDeck:Deck = Deck()
var propertiesDeck:Deck = Deck()
init()
{
self.gameState = .Initialize
self.playerOnTurn = nil // No player on turn when game is initialized
self.seedCash = kInitialSeedCash
}
func setup(numberOfPlayers:Int)
{
// Create decks of properties and cheques
self.propertiesDeck = Deck.createProperties()
self.chequesDeck = Deck.createCheques()
}
}
Deck class is as follows
// Deck of cards
// Two deck types in the game - (1) Properties & (2) Cheques
class Deck
{
private var cards:[Card] = [] // Empty Array
// #return: An array of cards
func createProperties() -> [Card]
{
var propertyDeck:[Card] = []
// TODO: - Needs Local JSON reader
let prop1 = Card.init(name:"Cardboard box", value:1)
propertyDeck.append(prop1)
let prop2 = Card.init(name:"Outhouse", value:2)
propertyDeck.append(prop2)
let prop3 = Card.init(name:"Outhouse", value:3)
propertyDeck.append(prop3)
return propertyDeck
}
// #return: An array of cards
func createCheques() -> [Card]
{
var chequeDeck:[Card] = []
// create 2 copies of each card, but skip 1s
for var i:Int = 0; i<=15; i++
{
if (i != 1)
{
let chequeCard = Card.init(name: "Cheque", value: i * 1000)
chequeDeck.append(chequeCard)
}
}
return chequeDeck
}
func addCard()
{
}
func shuffle()
{
}
}
Deck() is a class
func setup() {
var propertiesDeck:Deck = Deck()
// Create property deck
self.propertiesDeck = Deck.createProperties()
}
// Deck.createProperties file
// #return: An array of cards
func createProperties() -> [Card]
{
var propertyDeck:[Card] = []
let prop1 = Card.init(name:"Penthouse", value:1)
propertyDeck.append(prop1)
return propertyDeck
}
But Swift keeps complaining that;
Missing argument for parameter #1 in call
But there aren't any arguments or parameters.
Perhaps I'm doing something wrong/silly?
This error would generally say that Deck is expecting some constructor parameters. Could you please post your Deck class so I can see if there are any?
Also some more suggestions. You seem to be creating the Deck variable propertiesDeck, but then statically accessing createProperties by stating Deck.createProperties(). Should you not be calling propertiesDeck.createProperties()? Also createProperties is returning an Array of the Card object, but propertiesDeck is a Deck class.
Since you're accessing your function like this:
Deck.createProperties()
you probably want a static method instead:
static func createProperties() -> [Card] {
...
}
Which shouldn't give you an error anymore.
Another way to make it work is by calling createProperties() on your already defined Deck like this (not recommended):
self.propertiesDeck = propertiesDeck.createProperties()
The reason for the missing parameter comes from the fact that methods take the class instance as their first parameter, so you could actually call it like Deck.createProperties(propertiesDeck)().
I believe you've got some other flaws in your code, I will try to make a better example for you:
struct Card {
let name : String
let value : Int
}
class Deck {
var cards : [Card]
init() {
cards = [
Card(name: "Penthouse", value: 1)
]
}
}
Try This,
func createProperties() -> [Card]
{
var propertyDeck:[Card] = []
let prop1 = Card(name:"Penthouse", value:1)
propertyDeck.append(prop1)
return propertyDeck
}
If this does not works then show the code for the class Deck and Card.
We can't answer your question without the complete code. We need the code of your Deck class.
But you can try class funcs...
public class Cards {
class func createProperties() -> [Card]
{
var propertyDeck:[Card] = []
let prop1 = Card.init(name:"Penthouse", value:1)
propertyDeck.append(prop1)
return propertyDeck
}
} 
You can call the function with:
Cards.createProperties()

Custom class in Swift conversion

I have created a custom class called PhoneTranslator (based on Xamarin's "Hello, iOS" guide). It looks like this:
class PhoneTranslator {
func ToNumber(raw:String) -> String {
var newNumber = raw.isEmpty ? "" : raw.uppercaseString
//newNumber operations...
return newNumber
}
}
Then I have a ViewController standard class. I want to do this:
var translatedNumber : String?
if let inputText = PhoneNumberTextField.text //getting text from UITextField
{
translatedNumber = PhoneTranslator.ToNumber(inputText) //error
}
Then in line with ToNumber method I get an error Cannot convert value of type 'String' to expected argument type 'PhoneTranslator'.
What am I doing wrong? All input and output types seems to match.
Change your code to
class PhoneTranslator {
class func ToNumber(raw:String) -> String {
var newNumber = raw.isEmpty ? "" : raw.uppercaseString
return newNumber
}
}
Your function was not a class function. Therefore you need an instance first. Above code defines the ToNumber function as class func.
Alternatively create an instance of the PhoneTranslator first:
translatedNumber = PhoneTranslator().ToNumber(inputText)
Note the () after PhoneTranslator.
Alternatively no need to make a class function. You can have a shared Instance which will be a singleton object for the entire application. With this singleton object you can call the PhoneTranslator methods
class PhoneTranslator {
static let sharedInstance = PhoneTranslator()
func ToNumber(raw:String) -> String {
var newNumber = raw.isEmpty ? "" : raw.uppercaseString
//newNumber operations...
return newNumber
}
}
And you can call it this way
translatedNumber = PhoneTranslator.sharedInstance.ToNumber(inputText)

my swift method gives no output

I don't really know what is wrong with this that i cant get any output
class Shape {
var numberOfSides : Int = 3
var name : String
init(name : String){
self.name = name
}
func print() -> String {
return("numberOfSides : \(numberOfSides)")
}
}
var Square = Shape("moraba")
println(Square.print())
Unlike normal methods and functions init() methods require to pass the first parameter name
let square = Shape(name:"moraba")
println(square.print())