Swift - Bool vs Boolean - swift

I am teaching myself to program using Swift 3, and I am currently learning about booleans. I noticed that if I want to explicitly declare my variable of type bool, I have two options
Bool
or
Boolean
I was wondering why we have these two options if they are the same? Well, are they the same? This is what I'm confused about.
Thanks in advance.

Bool is Swift's boolean data type. Boolean hasn't existed since the early days of Swift.

Related

Why use T! instead of T as function parameter and return type? [duplicate]

This question already has answers here:
In Swift, what does the ! symbol mean in a function signature?
(2 answers)
Closed 3 years ago.
In JavaScriptCore, I saw most of functions declared T! as parameter type and return type. Since T! assumes non-nil when pass in and return, why not just declare T as type?
e.g.
func evaluateScript(_ script: String!) -> JSValue!
why not just
func evaluateScript(_ script: String) -> JSValue
This indicates that an ObjC API has not yet been audited for nullability, and does not have nullability annotations applied. Without nullability annotations, the compiler doesn't know whether the values are optional or not. The default behavior in that case is to make them all ! types, and leave the question to the caller (the only other possible approach would be to make everything ? types, which would be extremely inconvenient to work with).
When Apple annotates the header, the ! will go away.
In the meantime, it's up to you to check the documentation to ensure the return values cannot be nil before using them directly.
In this particular case, the underlying JSEvaluateScript can in fact return nil:
#result The JSValue that results from evaluating script, or NULL if an exception is thrown.
So you do need to check it. There's just no way for the compiler to know that currently.

What types cannot be cast to `AnyObject` in Swift 4?

I've experimented with casting many types to AnyObject. Reference types obviously cast unaltered, but others are automagically converted under the hood to NSNumber, NSValue, and so on. (These are not the exact types, but close enough.) I was even able to cast a tuple successfully.
This surprised me. Are there any types that cannot be cast to AnyObject?
There are other questions and answers that may cover this material, but none of them asks this question specifically and the answer to this question can only be found in the fine print of the other answers.
AnyObject is Objective-C id, meaning any class type. Casting to AnyObject means "wrap this up in a way that Objective-C can deal with as a class type."
Obviously, an NSObject subclass just crosses the bridge directly.
For other types (i.e. nonclasses), Swift 4 follows three policies:
Some types are bridged directly to classes, e.g. String to NSString.
Some types are wrapped in Objective-C class types, e.g. Int in NSNumber or CGRect in NSValue.
All other types are boxed in an opaque wrapper; they can cross the bridge to Objective-C, and can be round-tripped successfully back to Swift, but nothing useful can be done with them in the Objective-C world.

Boolean extension function

When I try to create Extension Function to set Boolean true or false like the below.
Boolean.setTrue(){
this = true
}
Boolean.setFalse(){
this = false
}
It says variable expected. How to achieve this.
You cannot change the value of this, this would break a lot of assumptions, even if you could you would not be able to change the value, as Booleans are immutable.
More generally, there is a fine line between simplifying code, and making it more complex, and in this case that would complicate it. I would agree that adding String.splitByDot() may make sense, but replacing idiomatic code tends to just make the code more complex, as you start to wonder why the code had to be replaced.
Sorry but this does not make sense. Just use myBool=false, it's what anyone understands and cannot get any more readable.
Also Boolean is immutable and what you're trying isn't possible anyways.
We have to be careful not to overuse extensions. It's one of the greatest features Kotlin (and others) offers, but in certain examples, e.g. trying to change the way a dead simple Boolean is being assigned, it's getting dangerous IMHO (luckily it's not possible).
Here is an extension method that works in C# 7.2 or later:
public static class Extensions
{
public static bool Toggle(ref this bool b) => b = !b;
}
Then elsewhere, something like this will work:
bool b1 = true; // Works for primitive bool type.
Boolean b2 = true; // Works for Boolean object, too.
b1.Toggle();
b2.Toggle();
The only benefit I see to using an extension method is to shorten lines with long bool expressions, such as replacing:
this.SomeObjectWithALongName.SomeVerboselyNamedProperty
= !this.SomeObjectWithALongName.SomeVerboselyNamedProperty
with
this.SomeObjectWithALongName.SomeVerboselyNamedProperty.Toggle();
I don't know what drawbacks this extension method may have.
The reason you can't do this is that you cannot reassign the receiver in an extension function.
It's not possible to change the value of the Boolean because it is immutable.
The reason you can do this comes to a lack of implementation of Kotlin extension probably due to the fact Extension in Kotlin are resolved Statically (even probably really static).
So 'this' in a static context doesn't make sense.

Swift dynamic type checking for structs?

I'm confused about dynamic type checking in Swift.
Specifically, I have a weirdo case where I want to, essentially, write (or find) a function:
func isInstanceOf(obj: Any, type: Any.Type) -> Bool
In Objective-C, this is isKindOfClass, but that won't work because Any.Type includes Swift structs, which are not classes (much less NSObject subclasses).
I can't use Swift is here, because that requires a hardcoded type.
I can't use obj.dynamicType == type because that would ignore subclasses.
The Swift book seems to suggest that this information is lost, and not available for structs at all:
Classes have additional capabilities that structures do not:
...
Type casting enables you to check and interpret the type of a class instance at runtime.
(On the Type Casting chapter, it says "Type casting in Swift is implemented with the is and as operators", so it seems to be a broader definition of "type casting" than in other languages.)
However, it can't be true that is/as don't work with structures, since you can put Strings and Ints into an [Any], and pull them out later, and use is String or is Int to figure out what they were. The Type Casting chapter of the Swift Book does exactly this!
Is there something that's as powerful as isKindOfClass but for any Swift instances? This information still must exist at runtime, right?
Actually you can use is operator.
Use the type check operator (is) to check whether an instance is of a certain subclass type. The type check operator returns true if the instance is of that subclass type and false if it is not.
Since struct can't be subclassed, is is guaranteed to be consistent when applied to instance of struct because it will check on it static type, and for classes it will query the dynamic type in runtime.
func `is`<T>(instance: Any, of kind: T.Type) -> Bool{
return instance is T;
}
This work for both, struct and class.
As already stated, is/as should work fine with structs. Other corner cases can usually be done with generic functions, something like:
let thing: Any = "hi" as Any
func item<T: Any>(_ item: Any, isType: T.Type) -> Bool {
return (item as? T) != nil
}
print(item(thing, isType: String.self)) // prints "true"
No idea if this fits your specific use case.
More generally, keep in mind that Swift (currently) requires knowing the type of everything at compile time. If you can't define the specific type that will be passed into a function or set as a variable, neither will the compiler.

Are Int, String etc. considered to be 'primitives' in Swift?

Types representing numbers, characters and strings implemented using structures in swift.
An excerpt from the official documentation:
Data types that are normally considered basic or primitive in other
languages—such as types that represent numbers, characters, and
strings—are actually named types, defined and implemented in the Swift
standard library using structures.
Does that mean the following:
Int
Float
String
// etc
... are not considered as primitives?
Yes and no...
As other answers have noted, in Swift there's no difference at the language level between the things one thinks of as "primitives" in other languages and the other struct types in the standard library or the value types you can create yourself. For example, it's not like Java, where there's a big difference between int and Integer and it's not possible to create your own types that behave semantically like the former. In Swift, all types are "non-primitive" or "user-level": the language features that define the syntax and semantics of, say, Int are no different from those defining CGRect or UIScrollView or your own types.
However, there is still a distinction. A CPU has native instructions for tasks like adding integers, multiplying floats, and even taking vector cross products, but not those like insetting rects or searching lists. One of the things people talk about when they name some of a language's types "primitively" is that those are the types for which the compiler provides hooks into the underlying CPU architecture, so that the things you do with those types map directly to basic CPU instructions. (That is, so operations like "add two integers" don't get bogged down in object lookups and function calls.)
Swift still has that distinction — certain standard library types like Int and Float are special in that they map to basic CPU operations. (And in Swift, the compiler doesn't offer any other means to directly access those operations.)
The difference with many other languages is that for Swift, the distinction between "primitive" types and otherwise is an implementation detail of the standard library, not a "feature" of the language.
Just to ramble on this subject some more...
When people talk about strings being a "primitive" type in many languages, that's a different meaning of the word — strings are a level of abstraction further away from the CPU than integers and floats.
Strings being "primitive" in other languages usually means something like it does in C or Java: The compiler has a special case where putting something in quotes results in some data getting built into the program binary, and the place in the code where you wrote that getting a pointer to that data, possibly wrapped in some sort of object interface so you can do useful text processing with it. (That is, a string literal.) Maybe the compiler also has special cases so that you can have handy shortcuts for some of those text processing procedures, like + for concatenation.
In Swift, String is "primitive" in that it's the standard string type used by all text-related functions in the standard library. But there's no compiler magic keeping you from making your own string types that can be created with literals or handled with operators. So again, there's much less difference between "primitives" and user types in Swift.
Swift does not have primitive types.
In all programming languages, we have basic types that are available part of the language. In swift, we have these types availed through the Swift standard library, created using structures. These include the types for numbers, characters and strings.
No, they're not primitives in the sense other languages define primitives. But they behave just like primitives, in the sense that they're passed by value. This is consequence from the fact that they're internally implemented by structs. Consider:
import Foundation
struct ByValueType {
var x: Int = 0;
}
class ByReferenceType {
var x: Int = 0;
}
var str: String = "no value";
var byRef: ByReferenceType = ByReferenceType();
var byVal: ByValueType = ByValueType();
func foo(var type: ByValueType) {
type.x = 10;
}
func foo(var type: ByReferenceType) {
type.x = 10;
}
func foo(var type: String) {
type = "foo was here";
}
foo(byRef);
foo(byVal);
foo(str);
print(byRef.x);
print(byVal.x);
print(str);
The output is
10
0
no value
Just like Ruby, Swift does not have primitive types.
Int per example is implemented as structand conforms with the protocols:
BitwiseOperationsType
CVarArgType
Comparable
CustomStringConvertible
Equatable
Hashable
MirrorPathType
RandomAccessIndexType
SignedIntegerType
SignedNumberType
You can check the source code of Bool.swift where Bool is implemented.
There are no primitives in Swift.
However, there is a distinction between "value types" and "reference types". Which doesn't quite fit with either C++ or Java use.
They are partial primitive.
Swift not exposing the primitive like other language(Java). But Int, Int16, Float, Double are defined using structure which behaves like derived primitives data type(Structure) not an object pointer.
Swift Documentation favouring to primitive feature :
1.They have Hashable extension say
Axiom: x == y implies x.hashValue == y.hashValue.
and hashValue is current assigned value.
2.Most of the init method are used for type casting and overflow check (remember swift is type safe).
Int.init(_ other: Float)
3. See the below code Int have default value 0 with optional type. While NSNumber print nil with optional type variable.
var myInteger:Int? = Int.init()
print(myInteger) //Optional(0)
var myNumber:NSNumber? = NSNumber.init()
print(myNumber) //nil
Swift Documentation not favouring to primitive feature :
As per doc, There are two types: named types and compound types. No concept of primitives types.
Int support extension
extension Int : Hashable {}
All these types available through the Swift standard library not like standard keyword.