How can we transfer data between classes when using swift programming language - swift

With Objective-C we could transfer data to an array at an UIView class from ViewController using a method.
In an UIView class we were using something like this
float values[10];
-(void) getValue:(float) value index:(int) index {
values[index] = value
}
But when we try doing a similar thing with Swift such as
var values : [CGFloat] = [10]
func getValue (value:CGFloat, index:Int) {
values [index] = value
}
We are getting " fatal error: Array index out of range error " or if we use
var values : [CGFloat] = [10]
var index = 0
func getValue (value:CGFloat) {
values.append = value
++index
}
We are not getting error message but whenever we use setNeedsDisplay() array values are being set to initial values which is 10 for this example.
Till now we are unable to convert Objective-C UIView classes like that to Swift one.

First:
var values : [CGFloat] = [10]
That line says that values is a variable array of CGFloat values that currently holds a single value of 10. Therefore, only index 0 actually exists.
Also:
func getValue(value:CGFloat, index:Int) {
values [index] = value
}
Never mind the fact that you have put this on the UIView class, never mind that you have a method named "getValue" that actually sets a value...
EDIT:
I found a better solution:
var values = Array<Float>(count:10, repeatedValue: 0)
func getValue(value: Float, index: Int) {
values[index] = value
}
The above is the direct Swift equivalent to the Objective-C code you posted in your question.
Frankly, I think you should take a step back and find a better way to solve the problem you think this code is solving. As it stands it doesn't make a whole lot of sense.

var values : [CGFloat] = [10]
In swift, this will create an array of CGFloat with one element: 10.0, not 10 elements.
so values.count is one
Swift Collections

Yes, after studying some more Swift I found the answer to my question.
Using static variable in the UIView class is the answer.
Define variable like that in UIView class
struct StructToChange {
static var varToChange = 1
}
Write a function to change variable value like this in UIView class.
func getIt (newValue:Int) {
StructToChange.varToChange = newValue
}
Call the function in a controller class this way
let valueChanger = AnyUIViewClass()
valueChanger.getIt ( 10 )
This is it you changed the value of variable and you can use it as parameter in your " override func drawRect(rect: CGRect) { } "

Related

Variable 'xxx' was never mutated; in derived class

I'm posting my first message here, I've a logical question about swift language. For your information, I'm quite new in swift language, I'm use to code in c++ and it's a bit hard for me to have an objective point of view on how to do things right (in an elegant way), if you have some advices, pls feel free to do your suggestions.
I'm doing a homemade encapsulation using the following superclass :
class MultiLevel_encapsulation {
var separator = "";
var datas:[String:String] = [:]
func wrap() -> String{
var out:String = ""
var i = 0
for (key, data) in datas{
if i==0{
out += key + separator + data
}
else{
out += separator + key + separator + data
}
i+=1
}
return out
}
func unwrap(content:String){
let split = content.components(separatedBy: separator)
var i = 1
while(i < split.count){
datas[split[i-1]] = split[i]
i += 2
}
}
func getAttributesNames() -> [String]{
var out:[String] = []
for (key, _) in datas{
out.append(key)
}
return out
}
func getValue(name:String) -> String? {
return datas[name];
}
func setValue(name:String, value:String){
datas[name] = value;
}
}
and I want to create some subclasses including the superclass, I just change the separator depending of the subclass name :
class Level5_encapsulation: MultiLevel_encapsulation{
init(message:String) {
super.init()
separator = "&&LEVEL5&&"
unwrap(content:message)
}
override init() {
super.init()
separator = "&&LEVEL5&&"
}
}
So after it I just need to create the subclass as a var in my program, add values and wrap it to have an encapsulated string :
var l5message = Level5_encapsulation()
l5message.setValue(name: #anyTitle#, value: #anyValue#)
var output = l5message.wrap() // String with encapsulated message
Do you think it 's the right way to do it or is there a better way for that ?
My main question is about this compiler warning :
Variable 'l5message' was never mutated; consider changing to 'let' constant
I changed it for a let and it works.
So there is something I don't understand : Why can I change proprieties in the superclass as if the inherited subclass is declared as constant ? Where is the storage of the superclass and how does it works ?
In Swift classes and structs behave a bit differently than in C++. var and let prevent changes to the actual value, and since the variable type that you're using is a class the variable holds a reference, and not the actual data (Like Level5_encapsulation *l5message).
Since you're not mutating the value of the variable (A reference), the compiler raises a warning.

Swift - Declare nested variable names using dot

I'll keep it short. I'm trying to accomplish the following:
class Media {
var likes.count : Int? = 0
}
Obviously the complier throws me an error:
Consecutive declarations on a line must be separated by ';'
Is there a way to work around this? I know that i can eventually do some kind of String Replace using Mirror(reflecting:object) but i'd like to keep it efficient. Would love any help. Thanks.
UPDATE:
I wasn't clear enough, sorry. The issue is that the complier won't let me use . inside the variable declaration name.
The issue is that the complier won't let me use . inside the variable declaration name.
Exactly, a property name in Swift cannot contain the . character.
A possible approach
Now, if you want to be able to write something like this
let media = Media()
media.likes.count = 1
then you need to define your class like shown below
class Media {
class Likes {
var count = 0
}
var likes = Likes()
}
or
class Likes {
var count = 0
}
class Media {
var likes = Likes()
}
A few suggestions
PLEASE don't use implicitly unwrapped optionals like this one
var likes.count : Int! = 0
They are like a gun ready to fire and crash your entire app!
And finally the class keyword begins with a lowercase character: class not Class.
I recommend using a Struct. A Struct is basically the same as a class that is referenced by value. So you can have as many Structs as you want with their own nested variables and functions, just like a class! And the best part is, you never have to use the Struct as a functional piece of code, just as something to namespace your variables in. I do this frequently with a Constants swift file.
struct Constants {
struct MainMenu {
static var height:CGFloat = 420
static var width:CGFloat = 240
static var backgroundColor:UIColor = .red
}
struct MainViewController {
static var toolBarHeight:CGFloat = 49
static var backgroundColor:UIColor = .blue
}
}
Usage:
func getRemainingHeight() ->CGFloat {
let viewHeight = self.view.bounds.size.height
let menuHeight = Constants.MainMenu.height
let toolBarHeight = Constants.MainViewController.toolBarHeight
return viewHeight - (menuHeight + toolBarHeight)
}

How to convert String to Int in Swift?

There has been same titles of this question but different situations.
In this case this is very simple but I can't find a same problem online.
So here's the code
class ViewController: UIViewController {
#IBOutlet weak var fldTotalUnits: UITextField!
var intTotalUnits:Int? = Int(fldTotalUnits)
The error here says "Cannot use instance member 'fldTotalUnits' within property initializer;..."
I tried replacing var with let, I tried NSString, I tried .toInt() but nothign worked... so how do I this?
String to Int conversion is not complicated. You simply do the conversion at the wrong place. You are trying to reference one member in the initialization of another member, that is not allowed. In this particular case simply because fldTotalUnits has the value nil when you would try to use it via Int(fldTotalUnits). When creating an instance of your class ViewController fldTotalUnits is set to nil and initialized with a useful value later. Therefore what you have to do in the first place is move the line into a separate method:
func doSomething() {
var intTotalUnits:Int? = Int(fldTotalUnits)
}
Now you will see that the compiler complains about there not being a suitable initializer because you have to access the text property of fldTotalUnits instead of using the actual textfield:
func doSomething() {
var intTotalUnits:Int? = Int(fldTotalUnits.text!)
}
Now you can think about moving the declaration of intTotalUnits to somewhere else, but setting its value has to happen in some method.
The code in your question is trying to create an Int from a UITextField, not a String. What you should say is something likeā€¦
var intTotalUnits:Int?
func updateTotalUnits()
guard let text = fldTotalUnits.text else { return }
intTotalUnits = Int(text)
}

How can I create an extension method that only applies to Arrays of nullable items [duplicate]

Can I make an Array extension that applies to, for instance, just Strings?
As of Swift 2, this can now be achieved with protocol extensions,
which provide method and property implementations to conforming types
(optionally restricted by additional constraints).
A simple example: Define a method for all types conforming
to SequenceType (such as Array) where the sequence element is a String:
extension SequenceType where Generator.Element == String {
func joined() -> String {
return "".join(self)
}
}
let a = ["foo", "bar"].joined()
print(a) // foobar
The extension method cannot be defined for struct Array directly, but only for all types
conforming to some protocol (with optional constraints). So one
has to find a protocol to which Array conforms and which provides all the necessary methods. In the above example, that is SequenceType.
Another example (a variation of How do I insert an element at the correct position into a sorted array in Swift?):
extension CollectionType where Generator.Element : Comparable, Index : RandomAccessIndexType {
typealias T = Generator.Element
func insertionIndexOf(elem: T) -> Index {
var lo = self.startIndex
var hi = self.endIndex
while lo != hi {
// mid = lo + (hi - 1 - lo)/2
let mid = lo.advancedBy(lo.distanceTo(hi.predecessor())/2)
if self[mid] < elem {
lo = mid + 1
} else if elem < self[mid] {
hi = mid
} else {
return mid // found at position `mid`
}
}
return lo // not found, would be inserted at position `lo`
}
}
let ar = [1, 3, 5, 7]
let pos = ar.insertionIndexOf(6)
print(pos) // 3
Here the method is defined as an extension to CollectionType because
subscript access to the elements is needed, and the elements are
required to be Comparable.
UPDATE: Please See Martin's answer below for Swift 2.0 updates. (I can't delete this answer since it is accepted; if Doug can accept Martin's answer, I'll delete this one to avoid future confusion.)
This has come up several times in the forums, and the answer is no, you can't do this today, but they get that it's a problem and they hope to improve this in the future. There are things they would like to add to stdlib that also need this. That's why there are so many free functions is stdlib. Most of them are work-arounds for either this problem or the "no default implementation" problem (i.e. "traits" or "mixins").
This has already been answered by the three wise-men above ;-) , but I humbly offer a generalization of #Martin's answer. We can target an arbitrary class by using "marker" protocol that is only implemented on the class that we wish to target. Ie. one does not have to find a protocol per-se, but can create a trivial one for using in targeting the desired class.
protocol TargetType {}
extension Array:TargetType {}
struct Foo {
var name:String
}
extension CollectionType where Self:TargetType, Generator.Element == Foo {
func byName() -> [Foo] { return sort { l, r in l.name < r.name } }
}
let foos:[Foo] = ["c", "b", "a"].map { s in Foo(name: s) }
print(foos.byName())
You still haven't given a use case, despite many requests in comments, so it's hard to know what you're after. But, as I've already said in a comment (and Rob has said in an answer), you won't get it literally; extensions don't work that way (at the moment).
As I said in a comment, what I would do is wrap the array in a struct. Now the struct guards and guarantees the string's type, and we have encapsulation. Here's an example, though of course you must keep in mind that you've given no indication of the kind of thing you'd really like to do, so this might not be directly satisfying:
struct StringArrayWrapper : Printable {
private var arr : [String]
var description : String { return self.arr.description }
init(_ arr:[String]) {
self.arr = arr
}
mutating func upcase() {
self.arr = self.arr.map {$0.uppercaseString}
}
}
And here's how to call it:
let pepboys = ["Manny", "Moe", "Jack"]
var saw = StringArrayWrapper(pepboys)
saw.upcase()
println(saw)
Thus we have effectively insulated our string array into a world where we can arm it with functions that apply only to string arrays. If pepboys were not a string array, we couldn't have wrapped it in a StringArrayWrapper to begin with.

How do I initialize a property that depends on another property, when I don't have access to self yet?

I have two properties in my class. See this terrible example:
var length
var doubleLength
How do I initialize doubleLength based on length?
init() {
self.length = ...
self.doubleLength = self.length * 2
super.init()
}
I get an error that I can't access self before I call super.init(). Well I need to set all my variables before I can even call super.init() so what am I supposed to do?
if self.doubleLength is always supposed to be twice self.length (in this example) have you considered just using a computed property?
class MyClass: MySuperClass {
var length: Double
var doubleLength: Double {
return self.length * 2
}
init(len: Double) {
self.length = len
super.init()
}
}
You can temporarily delay the initialization of doubleLength an implicitly unwrapped optional, which will allow to temporarily assign a value to nil and assign it at a later time.
class Something: UICollectionViewLayout {
var doubleLength: Int! = nil
var length: Int {
return 50
}
init() {
super.init()
doubleLength = length * 2
}
}
Anyway, in this specific case I think it would be nicer to make doubleLength a computed property, since it can be always be computed from the value of length. Your class will be like
class Something: UICollectionViewLayout {
var doubleLength: Int {
return length * 2
}
var length: Int {
return 50
}
}
Thanks for your full reproduction, which is:
import UIKit
class Something: UICollectionViewLayout {
var doubleLength: Int
var length: Int {
return 50
}
init() {
doubleLength = length * 2
super.init()
}
}
From this we can see that you're using a getter to return your property. I think this is what's causing the problem. For example, if you just do this:
import UIKit
class Something: UICollectionViewLayout {
var doubleLength: Int
// Simple variable, no code.
var length = 50
init() {
doubleLength = length * 2
super.init()
}
}
...then that works fine.
I believe this is because the Swift compiler is trying to prevent you from doing anything that might mean you use the base class's methods, properties or variables before it's been initialised. I know you're technically not, in your example, but consider how hard it is to trace back and see what's being done from your initialiser. For example, if you were to do:
var length: Int {
// Where "width" is a made-up property of UICollectionViewLayout
return width * 3
}
...then your code would be run from your initialiser and use a property of UICollectionViewLayout before its own init had been called, therefore making it possibly invalid.
So my best guess is that this is the Swift compiler making a blanket ban on calling out to any code outside the subclass initialiser before the super is initialised.
You get exactly the same error if you do this, for example:
class Something: UICollectionViewLayout {
func foo() {
// Do nothing
}
init() {
foo() // error: 'self' used before super.init call
super.init()
}
}
The place I remember this being explained is the "Intermediate Swift" video from WWDC 2014, from slide 191, about 20 minutes in, but I'm guessing it's somewhere in the book, too...
A property that depends on another is bad practice. Just like when you design a database, you avoid calculated fields, when you design classes, you also avoid calculated fields. Instead of having a doubleLength property, you should instead have a getDoubleLength method that returns the length * 2.