Public Extensions in Swift : Float vs Float.type - swift

I'm trying to build an extension for floats in Swift that returns an enum (case .Positive for positive, .Negative for negative). I built an enum first.
public enum Sign
{
case Positive,Negative
}
Now, for the extension,
public extension Float
{
public static func sign()-> Sign
{
if self < Float(0)
{
return Sign.Negative
}
else
{
return Sign.Positive
}
}
}
I'm getting
Cannot convert value of type 'Float.Type' to expected argument type
For the line
if self < Float(0)
But that shouldn't be happening, considering that 'self' inside an extension for Float, should remain a float.

Because you are using static:
public static func sign()-> Sign { ... }
self in this function refers to the type (the Float struct) rather than the instance (a floating point number). Remove the static and you'll be fine.

First thing you are using it with static as #codedifferent already explained and second if there is already a property isMinus then why are using your own logic?
Simply use this to reduce number of lines of code:
public extension Float {
public func sign()-> Sign {
return self.isSignMinus ? Sign.Negative : Sign.Positive
}
}

Related

Can I make my own getters and setters and should I?

Should I make my own getters and setters in Swift? Im confused by the built in getters ad setters...is this even needed?
//properties for the resident
private var name: String!
var apartmentNumber: String!
var email : String!
var phoneNumber : String!
public func getName()->String{
return self.name
}
public func setName(name : String){
self.name = name
}
}
I've written an article for exactly this. I'll paste it here.
Stop writing getters and setters in Swift
I see this time and time again, and it's about time I write an article in one place to consolidate all my thoughts. If you find yourself writing code that looks like this, listen up:
public class C {
private var _i: Int = 0
public var i: Int {
get {
return self._i
}
set {
self._i = newValue
}
}
}
This pattern* is completely pointless in Swift, and I'll explain why, but firstly we need to take a short detour through Java land. Why Java? Because most of the people I run into who write Swift like this have some sort of Java background, either
because it was taught in their computer sceince courses, or
because they're coming over to iOS development, from Android
What's the point of getters and setters?
Suppose we have the following class in Java:
public class WeatherReport {
public String cityName;
public double temperatureF;
public WeatherReport(String cityName, double temperatureF) {
this.cityName = cityName;
this.temperatureF = temperatureF;
}
}
If you showed this class to any CS prof, they're surely going to bark at you for breaking encapsulation. But what does that really mean? Well, imagine how a class like this would be used. Someone would write some code that looks something like this:
WeatherReport weatherReport = weatherAPI.fetchWeatherReport();
weatherDisplayUI.updateTemperatureF(weatherReport.temperatureF);
Now suppose you wanted to upgrade your class to store data in a more sensible temperature unit (beating the imperial system dead horse, am I funny yet?) like Celcius or Kelvin. What happens when you update your class to look like this:
public class WeatherReport {
public String cityName;
public double temperatureC;
public WeatherReport(String cityName, double temperatureC) {
this.cityName = cityName;
this.temperatureC = temperatureC;
}
}
You've changed the implementation details of your WeatherReport class, but you've also made an API breaking change. Because temperatureF was public, it was part of this class' API. Now that you've removed it, you're going to cause compilation errors in every consumer that depended on the exitense of the temperatureF instance variable.
Even worse, you've changed the semantics of the second double argument of your constructor, which won't cause compilation errors, but behavioural errors at runtime (as people's old Farenheit based values are attemped to be used as if they were celcius values). However, that's not an issue I'll be discussing in this article.
The issue here is that consumers of this class will be strongly coupled to the implementation details of your class. To fix this, you introduce a layer of seperation between your implementation details and your interface. Suppose the Farenheit version of our class was implemented like so:
public class WeatherReport {
private String cityName;
private double temperatureF;
public WeatherReport(String cityName, double temperatureF) {
this.cityName = cityName;
this.temperatureF = temperatureF;
}
public String getCityName() {
return this.cityName;
}
public void setCityName(String cityName) {
this.cityName = cityName;
}
public double getTemperatureF() {
return this.temperatureF;
}
public void setTemperatureF(double temperatureF) {
this.temperatureF = temperatureF;
}
}
The getters and setters are really basic methods that access or update our instance variables. Notice how this time, our instance variables are private, and only our getters and setters are public. A consumer would use this code, as so:
WeatherReport weatherReport = weatherAPI.fetchWeatherReport();
weatherDisplayUI.updateTemperatureF(weatherReport.getTemperatureF());
This time, when we make the upgrade to celcius, we have the freedom to change our instance variables, and tweak our class to keep it backwards compatible:
public class WeatherReport {
private String cityName;
private double temperatureC;
public WeatherReport(String cityName, double getTemperatureC) {
this.cityName = cityName;
this.temperatureC = temperatureC;
}
public String getCityName() {
return this.cityName;
}
public void setCityName(String cityName) {
this.cityName = cityName;
}
// Updated getTemperatureF is no longer a simple getter, but instead a function that derives
// its Farenheit value from the Celcius value that actuallyed stored in an instance variable.
public double getTemperatureF() {
return this.getTemperatureC() * 9.0/5.0 + 32.0;
}
// Updated getTemperatureF is no longer a simple setter, but instead a function
// that updates the celcius value stored in the instance variable by first converting from Farenheit
public void setTemperatureF(double temperatureF) {
this.setTemperatureC((temperatureF - 32.0) * 5.0/9.0);
}
// Mew getter, for the new temperatureC instance variable
public double getTemperatureC() {
return this.temperatureC;
}
// New setter, for the new temperatureC instance variable
public void setTemperatureC(double temperatureC) {
this.temperatureC = temperatureC;
}
}
We've added new getters and setters so that new consumers can deal with temperatures in Celcius. But importantly, we've re-implemented the methods that used to be getters and setters for temperatureF (which no longer exists), to do the appropraite conversions and forward on to the Celcius getters and setters. Because these methods still exist, and behave identically as before, we've successfully made out implementation change (storing F to storing C), without breaking our API. Consumers of this API won't notice a difference.
So why doesn't this translate into Swift?
It does. But simply put, it's already done for you. You see, stored properties in Swift are not instance variables. In fact, Swift does not provide a way for you to create or directly access instance variables.
To understand this, we need to have a fuller understanding of what properties are. There are two types, stored and computed, and neither of them are "instance variables".
Stored properties: Are a combination of a comiler-synthesized instance variable (which you never get to see, hear, touch, taste, or smell), and the getter and setter that you use to interact with them.
Computed proepties: Are just a getter and setter, without any instance variable to act as backing storage. Really, they just behave as functions with type () -> T, and (T) -> Void, but have a pleasant dot notation syntax:
print(weatherReport.temperatureC)
weatherReport.temperatureC = 100
rather than a function calling synax:
print(weatherReport.getTemperatureC())
weatherReport.setTemperatureC(100)
So in fact, when you write:
class C {
var i: Int
}
i is the name of the getter and setter for an instance variable the compiler created for you. Let's call the instance variable $i (which is not an otherwise legal Swift identifier). There is no way to directly access $i. You can only get its value by calling the getter i, or update its value by calling its setter i.
So lets see how the WeatherReport migration problem looks like in Swift. Our initial type would look like this:
public struct WeatherReport {
public let cityName: String
public let temperatureF: Double
}
Consumers would access the temperature with weatherReport.temperatureF. Now, this looks like a direct access of an isntance variable, but remember, that's simply not possible in Swift. Instead, this code calls the compiler-syntehsized getter temperatureF, which is what accesses the instance variable $temperatureF.
Now let's do our upgrade to Celcius. We will first update our stored property:
public struct WeatherReport {
public let cityName: String
public let temperatureC: Double
}
This has broken our API. New consumers can use temperatureC, but old consumers who depended on temperatureF will no longer work. To support them, we simply add in a new computed property, that does the conversions between Celcius and Fahenheit:
public struct WeatherReport {
public let cityName: String
public let temperatureC: Double
public var temperatureF: Double {
get { return temperatureC * 9/5 + 32 }
set { temperatureC = (newValue - 32) * 5/9 }
}
}
Because our WeatherReport type still has a getter called temperatureF, consumers will behave just as before. They can't tell whether a property that they access is a getter for a stored property, or a computed property that derives its value in some other way.
So lets look at the original "bad" code. What's so bad about it?
public class C {
private var _i: Int = 0
public var i: Int {
get {
return self._i
}
set {
self._i = newValue
}
}
}
When you call c.i, the following happens:
You access the getter i.
The getter i accesses self._i, which is yet another getter
The getter _i access the "hidden" instance variable $i
And it's similar for the setter. You have two layers of "getterness". See what that would look like in Java:
public class C {
private int i;
public C(int i) {
this.i = i;
}
public int getI1() {
return this.i;
}
public void setI1(int i) {
this.i = i;
}
public int getI2() {
return this.getI1();
}
public void setI2(int i) {
this.setI1(i);
}
}
It's silly!
But what if I want a private setter?
Rather than writing this:
public class C {
private var _i: Int = 0
public var i: Int {
get {
return self._i
}
}
}
You can use this nifty syntax, to specify a seperate access level for the setter:
public class C {
public private(set) var i: Int = 0
}
Now isn't that clean?
There is no need to create setters and getters for stored properties in Swift and you shouldn't create them either.
You can control the accessibility of getters/setters separately when you declare a property.
public private(set) var name: String // public getter, private setter
If you want to implement some custom logic in your setter, you should use property observer, i.e. didSet/willSet.
var name: String {
didSet {
// This is called every time `name` is set, so you can do your custom logic here
}
}
You will hardly come across the need to create your own getters and setters.
Swift's computed property lets you use getters and setters in a very simple way.
Eg: below defined is a computed property circleArea that returns area of circle depending on radius.
var radius: Float = 10
var circleArea: Float {
get {
return .pi * powf(radius, 2)
}
set {
radius = sqrtf(newValue / .pi)
}
}
While you can observe a stored value and perform some task using property observers:
var radius: Float = 10 {
willSet {
print("before setting the value: \(value)")
}
didSet {
print("after the value is set: \(value)")
}
}
radius += 1
// before setting the value: 10.0
// after the value is set: 11.0
However if you feel like using getter setter, you can define appropriate functions for that. Below defined is an extension on Integer to get and set properties value.
extension Int {
func getValue() -> Int {
return self
}
mutating func setValue(_ val: Int) {
self = val
}
}
var aInt: Int = 29
aInt.getValue()
aInt.setValue(45)
print(aInt)
// aInt = 45

How to port a complicated abstract class to swift?

I have an abstract class in my mind and I can't implement its several features in swift, so I use C++ to deliver my thoughts:
template <class T>
class Swapping {
public:
void swap() { _foregroundIndex = backgroundIndex() }
virtual void cleanup() = 0;
T* foreground() { return _buffer[foregroundIndex()]; }
T* background() { return _buffer[backgroundIndex()]; }
void setForeground(T* foreground) { _buffer[foregroundIndex()] = foreground; }
void setBackground(T* background) { _buffer[backgroundIndex()] = background; }
private:
short foregroundIndex() { return _foregroundIndex; }
short backgroundIndex() { return _foregroundIndex ^ 1; }
short _foregroundIndex = 0;
T* _buffer[2] = {NULL, NULL};
}
The main contradiction is that
The pure virtual method cleanup() requires all subclasses to implement it explicitly (can achieve in swift with protocol)
The instance variable _foregroundIndex has an initial value (cannot achieve using protocol)
The instance variable _foregroundIndex is restricted to be private ( cannot achieve using protocol)
On the other hand, if I use a class instead of protocol, then I can't guarantee cleanup() method is overriden.
One may suggest that put the virtual method in a protocol and the instance variable in a class. That may work but is not a obsession-satisfying one.
P.S. Objective-C is not Swift. Any objc_runtime related workaround is not preferred.
There’s an obvious solution, which I have seen often but will certainly not satisfy you is:
func cleanup() {
fatalError("You must override cleanup()")
}
Then you could try using extensions to extend the protocol with default implementations, but extensions don’t allow stored properties and so you would most likely need some external objects or other magic you certainly also dislike.
As I noted above in the comments, you might need to rethink your design. I don’t know what you really intend to do, but maybe something like this would work out for you:
class Swapper<T> {
private var foregroundIndex = 0
private var backgroundIndex: Int {
return foregroundIndex ^ 1
}
private var buffer: [T?] = [nil, nil]
private let cleanupHandler: () -> ()
init(cleanupHandler: #escaping () -> ()) {
self.cleanupHandler = cleanupHandler
}
func cleanup() {
cleanupHandler()
}
var foreground: T? {
get {
return buffer[foregroundIndex]
}
set {
buffer[foregroundIndex] = newValue
}
}
var background: T? {
get {
return buffer[backgroundIndex]
}
set {
buffer[backgroundIndex] = newValue
}
}
func swap() {
foregroundIndex = backgroundIndex
}
}
This makes more sense to me as this allows any types to be swapped with any clean up handler, without having to subclass the class every time.

Is it possible for protocols to have a default implementation of static factory methods?

Consider a protocol that have a factory method:
public protocol Frobnicator {
func frobnicate()
static func makeRightFrobnicator() -> Frobnicator
}
private class SomeFrobnicatorImplementation: Frobnicator { ... }
private class AnotherFrobnicatorImplementation: Frobnicator { ... }
public extension Frobnicator {
static func makeRightFrobnicator() -> Frobnicator {
if something {
return SomeFrobnicatorImplementation()
} else {
return AnotherFrobnicatorImplementation()
}
}
}
I want to be able to construct different implementors at different times. The implementors themselves are private to the module, whereas the protocol is public to use in the client code.
When I try the code similar to that above, I get “Static member makeRightFrobnicator cannot be used on protocol metatype Frobnicator.Protocol.”
Is there any way around it, or should I just use a free function?
The static function implementation is legal:
protocol P {
static func f() -> P
init()
}
extension P {
static func f() -> P {return self.init()}
}
But you'll notice that in order to get it to compile, I had to guarantee to the compiler that I have in hand a legal way to make a P so as to able to return one.
The issue in your code is the attempt to return a specific adopter of your protocol, like a SomeFrobnicatorImplementation. A protocol is agnostic as to who adopts it. To put it another way, you cannot guarantee within the protocol definition that SomeFrobnicatorImplementation will in fact be an adopter of this protocol. Thus, that part of your code is illegal.

Computed properties in Swift with getters and setters

I'm playing with the swift language and i have a question on get/set properties. I think that it makes no sense to let the inner variable be public when the value is managed by a computed property. So I think that making this private to the class is a good practise. As I'm still learning maybe some of you could give me other ideas to leave it public.
class aGetSetClass{
private var uppercaseString : String
var upperString : String {
get {
return uppercaseString
}
set (value) {
self.uppercaseString = value.uppercaseString
}
}
init(){
uppercaseString = "initialized".uppercaseString
}
}
var instance3 = aGetSetClass()
println(instance3.upperString) // INITIALIZED
instance3.upperString = "new"
// println(instance3.uppercaseString) // private no access
println(instance3.upperString) // NEW
instance3.upperString = "new123new"
println(instance3.upperString) // NEW123NEW
The only way I could think of public access is either to make it as private set and then use a public set function instead:
public private(set) uppercaseString: String
public func setUpperString(string: String) {
uppercaseString = string.uppercaseString
}
Or make it public and use a didSet which sets itself under a certain condition (very inefficient for long strings):
public uppercaseString: String {
didSet {
if uppercaseString != uppercaseString.uppercaseString {
uppercaseString = uppercaseString.uppercaseString
}
}
}
These implementations use direct public access but your version is in my perspective the better / "swifter" way.

Question about var type

I am new to C# 3.0 var type. Here I have a question about this type. Take the following simple codes in a library as example:
public class MyClass {
public var Fn(var inValue)
{
if ( inValue < 0 )
{
return 1.0;
}
else
{
return inValue;
}
}
}
I think the parameter is an anonymous type. If I pass in a float value, then the Fn should return a float type. If a double value type is passed in, will the Fn return a double type? How about an integer value type as input value?
Actually, I would like to use var type with this function/method to get different return types with various input types dynamically. I am not sure if this usage is correct or not?
You can't use var for return values or parameter types (or fields). You can only use it for local variables.
Eric Lippert has a blog post about why you can't use it for fields. I'm not sure if there's a similar one for return values and parameter types. Parameter types certainly doesn't make much sense - where could the compiler infer the type from? Just what methods you try to call on the parameters? (Actually that's pretty much what F# does, but C# is more conservative.)
Don't forget that var is strictly static typing - it's just a way of getting the compiler to infer the static type for you. It's still just a single type, exactly as if you'd typed the name into the code. (Except of course with anonymous types you can't do that, which is one motivation for the feature.)
EDIT: For more details on var, you can download chapter 8 of C# in Depth for free at Manning's site - this includes the section on var. Obviously I hope you'll then want to buy the book, but there's no pressure :)
EDIT: To address your actual aim, you can very nearly implement all of this with a generic method:
public class MyClass
{
public T Fn<T>(T inValue) where T : struct
{
Comparer<T> comparer = Comparer<T>.Default;
T zero = default(T);
if (comparer.Compare(inValue, zero) < 0)
{
// This is the tricky bit.
return 1.0;
}
else
{
return inValue;
}
}
}
As shown in the listing, the tricky bit is working out what "1" means for an arbitrary type. You could hard code a set of values, but it's a bit ugly:
public class MyClass
{
private static readonly Dictionary<Type, object> OneValues
= new Dictionary<Type, object>
{
{ typeof(int), 1 },
{ typeof(long), 1L },
{ typeof(double), 1.0d },
{ typeof(float), 1.0f },
{ typeof(decimal), 1m },
};
public static T Fn<T>(T inValue) where T : struct
{
Comparer<T> comparer = Comparer<T>.Default;
T zero = default(T);
if (comparer.Compare(inValue, zero) < 0)
{
object one;
if (!OneValues.TryGetValue(typeof(T), out one))
{
// Not sure of the best exception to use here
throw new ArgumentException
("Unable to find appropriate 'one' value");
}
return (T) one;
}
else
{
return inValue;
}
}
}
Icky - but it'll work. Then you can write:
double x = MyClass.Fn(3.5d);
float y = MyClass.Fn(3.5f);
int z = MyClass.Fn(2);
etc
You cannot use var as a return type for a method.