swift how to append UIColor in array - swift

my code is:
public var color = [UIColor]()
color.append(String(UIColor(dragInViews[i]!.backgroundColor)))
this code has an error:
Argument labels '(_:)' do not match any available overloads.
I'm trying to resolve problem but I don't know. What is the problem
how to resolve my problem?

You don't need the String() part (nor the UIColor() initializer), it's already a UIColor and the array is defined as an array of UIColor, so just appending it is more than enough.
public var color = [UIColor]()
color.append(dragInViews[i]!.backgroundColor)
Note that the backgroundColor property of a UIView is already a color, so there's no point in instantiating it again.
That particular error you're seeing is because you were trying to instantiate a color with its initializer in this way UIColor(something), but the initializer that exists is UIColor(white:, alpha:) between others. Check out the documentation here.

You need to create new array of UIColor type and in which you need to append color value not string type directly color
var arrColor = [UIColor]()
arrColor.append(UIColor(dragInViews[i]?.backgroundColor ?? UIColor()))

Related

How to save CGFloat and Color to realm DB?

I want to use realm to save data but as far as I understand realm does not support CGFloat and Color property, I searched for solution but it seems there is no answer.
Saving properties not supported by RealmSwift
In documentation said : “CGFloat properties are discouraged, as the type is not platform independent.”
In my app I use DragGesture and the value that returns for width and height are CGFloat this is my struct:
struct Card : Identifiable {
var id = UUID()
var name : String
var color : Color
var y : CGFloat = 0
var x : CGFloat = 0
}
and DB so far :
class cardDB : Object {
#objc dynamic var id = UUID()
#objc dynamic var name = ""
}
Is there any way to save these two property to realm DB?
Map CGFloat to Float.
I’m not sure what your Color type is. Assuming it’s like UIColor, and is in RGBA format, you should be able to create a struct containing Float values for red, green, blue, and alpha and save those.
Edit:
Your Card struct contains the following property:
var color : Color
That declares a variable color of type Color. Color Is not a system type. It might as well read
var color : CatFood
We have no idea what type Color type is. Based on the name, we can guess that it contains a description of a color, but that’s a guess.
You should command-click on the type Color in your project and select “jump to definition”. Then see what that type is. If it is an alias of UIColor or CGColor, great. If it is some custom type, add that definition to the bottom of your question.

How choose random element in swift?

I am absolutely new in swift and try to find a way for changing the color of labels randomly
for i in 1...20 {
let label = [label1, label2, label3]
let a = label.randomElement()
a.textColor = UIColor.orange // there is the problem
Any ideas?
Collection method randomElement() returns an optional. If your collection element is already optional you have a double optional. You need to use optional chaining or unwrap your optional.
a?.textColor = .orange // if your `a` label is of type `UILabel?` use a single exclamation mark

What is the purpose of "self" in Swift [duplicate]

This question already has answers here:
What is "self" used for in Swift?
(10 answers)
Closed 5 years ago.
I read many publications on "self" in Swift and I am starting to get a gist of it, but there is still one thing that is unclear to me.
class Car {
// 1
let make: String
// 2
private(set) var color: String
init() {
make = "Ford"
color = "Black"
}
required init(make: String, color: String) {
self.make = make
self.color = color
}
// 3
func paint(color: String) {
self.color = color
}
}
let car = Car(make: "Tesla", color: "Red")
car.paint("Blue")
I am trying to prove my point with help from the example above.
Several publications that I read indicate that self is used to distinguish 'color' from init() from the 'color' in the parameter from the func paint(color: String).
So when 'self color' is set in the func paint(color: String), which 'color' is it referring to? 'color' from the init() or color from the parameter of func paint(color: String)?
self is a reference to the current instance of the class in which the code is running.
In both the init method and the paint method, it allows you to specify that you wish to set the member variable named color using the value passed in the parameter to the method that is also called color.
The paint method cannot reference the parameter passed to init at all (nor vice versa).
So, in your sample code, both methods set the color of the object to some specified value passed in to the method as a parameter.
The init method sets an initial color for the object.
The paint method then allows you to change the color of the object from that initial color.
This might be clearer if the parameters were simply named differently, e.g.:
required init(initialMake: String, initialColor: String) {
self.make = initialMake
self.color = initialColor
}
func paint(newColor: String) {
self.color = newColor
}
In this case, since the functions are member methods, the self is now entirely optional since the compiler knows that color now can only mean the member called color since there is no other variable or parameter with that name, i.e. the paint method could be written simply as:
func paint(newColor: String) {
color = newColor
}
and this would have the exact same behaviour.
However, some people prefer to keep the self prefix for clarity, even where it isn't strictly required since as well as making the intent clear it can help avoid accidental mistakes if variables or member names are changed.
The self.color in both the init function and the paint function refer to the instance variable on the Car object.
To understand, think of the code without self:
func paint(color: String) {
color = color
}
The function's intent is for the car's color property to be the color passed into it. But with this code, it will not reference the car's color property, and the function wont work as intended. Thus, your function needs a little help in the form of the self keyword.
Also what would be the reason that init() is set up to automatically inititalize the value of "make" and "color" and then require you to initialize on your own after?
You're passing in values with your init function, you're not "automatically initializing the value of "make" and "color". The instance variables you have created for the Car object are non-optional values (Strings), so they cannot be nil, ever. So if you initialize a Car, you have to have their values correctly set after the init function is finished.
self references the object instance. Using self in Swift is optional in most cases.
It's needed in the code you posted because inside the init and the paint methods you have a parameter named color and you also want to access the property named color. Inside the methods, a reference to color will always be to the parameter. So the only way to indicate you want to reference the property named color, you must prefix the reference with self.. If you renamed the parameter so it didn't have the same name as the property, you wouldn't need self.
self.color will always mean a reference to the color property. color will first look for the nearest local variable/parameter of the same name. If found, that's what is used. If not, a property of the same name is used.

Can't set #IBInspectable computed property in UIView

I'm trying to add an IBInspectable color to UIView, so that I can set it in the storyboard and later use it in code. In this post regarding UITextField I've seen that I can take advantage of extensions and adding a computed property, but I can't make it work for UIView.
I get a crash: Failed to set (additionalColor1) user defined inspected property on (UIView): [ setValue:forUndefinedKey:]: this class is not key value coding-compliant for the key additionalColor1.
Any idea what's causing the crash and how to fix it?
Here's my code:
extension UIView {
#IBInspectable var additionalColor1: UIColor? {
return self.additionalColor1
}
}
For the reference, I'm pasting the code that can be used to set the placeholder color for UITextField (same as the above url). This works ok:
extension UITextField {
#IBInspectable var placeHolderColor: UIColor? {
get {
return self.placeHolderColor
}
set {
self.attributedPlaceholder = NSAttributedString(string: self.placeholder != nil ? self.placeholder! : "", attributes:[NSForegroundColorAttributeName: newValue!])
}
}
}
As mentioned in your question title
Swift extensions can only add computed properties to a type, but they cannot add stored properties.
(For more detailed information please refer to the Extension chapter in The Swift Programming Language.)
The example you posted is actually flawed — even if it has 50 upvotes on Stackoverflow at this time. If you return the value of a property itself from the property's getter you're creating a loop.
#IBInspectable var additionalColor1: UIColor? {
return self.additionalColor1
}
If you have a view and you try to access view.additionalColor1 anywhere in your code your property's getter will be called which returns self.additionalColor1 — or with other words: it returns the property's value again — and guess how? By calling the propery's getter! (And so on...)
The example from the post you mentioned only "works" because the getter is evidently never called. It's only setting that computed property placeHolderColor that changes another stored property, namely the text field's attributedPlaceholder.
So while you can add computed properties to an existing class through an extension you can never think of it as a concrete value that's stored somewhere. Computed properties may only be used to somehow transform the value you assign to it and store the result in existing stored properties.
How is your additionalColor going to be used?
I had to do something similar to this recently, but in my case I was always applying the extra value right away.
For example, I wanted to create a button that looked like a parallelogram. So, I wanted a way to put in a value in the Storyboard, which would apply a CGAffineTransform. I'm not really storing the skew value, just using to change what the thing looks like. Then, in the get, I'm passing back the value from the view's affineTransform routine.
#IBInspectable var skewOffset: Float {
set(newSkewOffset) {
let affineTransform : CGAffineTransform = CGAffineTransform(a: 1.0, b: 0.0, c: CGFloat(newSkewOffset), d: 1.0, tx: 0.0, ty: 0.0)
layer.setAffineTransform(affineTransform)
}
get {
return Float(layer.affineTransform().c)
}
}
So, I'm not storing skewOffset, I'm applying it, and I know how I can look it up later, if I need to get it.

Is it possible to evaluate a var/let with Swift?

Based upon this question: << Is the a ScriptEngine or eval()-like function in Swift? >> I'm assuming the following would not work in Swift:
private let BROWN_COLOUR: UIColor = UIColor.brownColor()
...
var colourName: String = "BROWN"
var colour = self[ colourName + "_COLOUR" ] as UIColor!
Correct or not?
Thank you for reading.
No, you cannot do that out of the box. You can, however, use keyed subscription to solve this. Or even easier: use a dictionary to store your values and query that.
But if the object derives from NSObject and the instance variables are marked with #objc, you can query these instance variables with valueForKey.