use of unresolved identifier 'println' in swift 3 [duplicate] - swift

This question already has answers here:
How do you do println() in swift 2 [duplicate]
(4 answers)
Closed 6 years ago.
I'm just a beginner with Swift. I am trying a very basic code, but unable to print things using 'println'.
This is my code,
import Cocoa
var myString:String? = nil
if myString != nil {
println(myString)
}else {
println("myString has nil value")
}

println() does not work in xcode. Instead, print() function is used to print a statement with a newline.
If instead, you were to want to print without a newline, a terminator is used
Try this for your code:
import Cocoa
var myString:String? = nil
if myString != nil {
print(myString)
} else {
print("myString has nil value")
}
Example with terminator:
import Cocoa
var myString:String? = nil
if myString != nil {
print(myString, terminator:"")
} else {
print("myString has nil value", terminator:"")
}

Related

Removing "Optional" in Swift 4 [duplicate]

This question already has answers here:
How do I prevent my text from displaying Optional() in the Swift interpolation?
(3 answers)
Closed 5 years ago.
That's my code
let temperature = String(describing: Int(incomeTemp.text!))
celcjuszScore.text = "\(temperature)"
print(temperature)
Whent I am pushing a button, the result of print is "Optional(32)" (When I am writing 32 in incomeTemp). I would like to have "Optional" removed and only "32" should stay.
Just unwrap it.
if let temperature = Int(incomeTemp.text!) {
celcjuszScore.text = "\(temperature)"
print(temperature)
}
Remove the optional when converting text to number: Int(incomeTemp.text!) ?? 0.
Or solve the error explicitly:
if let temperature = Int(incomeTemp.text ?? "") {
celcjuszScore.text = "\(temperature)"
} else {
celcjuszScore.text = "Invalid temperature"
}

swift 2.2 basic, if statement doesn't compile [duplicate]

This question already has an answer here:
Error "{ expected after if statement"
(1 answer)
Closed 6 years ago.
Pardon me for beginner's question, Why this code got complained about { expected after if, the braces are already there
var years = Int(edtYears.text!)
if years !=nil {
//do something
}else {
//...
}
Thanks
You need to add space between both side of condition like if years != nil { or you can also write without space but the both side if years!=nil {
var years = Int("")
if years != nil {
//do something
}else {
//...
}
Never do like this. Make sure you do optional chaining otherwise you will surely get a crash.
if let text = edtYears.text, let convertToInt = Int(text){
print("Int \(convertToInt)")
}else{
print("Cannot convert")
}

swift reflection causes impossible nil value for any

I'm trying to use swift reflection to check for changes in objects so I can send only changed properties up to the server. Some of my properties are optional. To compare those values, I need to unwrap them but, of course, you can ONLY unwrap actual values, not nil values. So, I need to check if one of the values is nil before I compare them.
In my playground, I tried the following:
import UIKit
class myClass
{
var fieldOne:String?
var fieldTwo:Int?
var fieldThree:Float?
}
var oneMyClass = myClass()
oneMyClass.fieldOne = "blah"
oneMyClass.fieldThree = 3.5
var oneOtherClass = myClass()
oneOtherClass.fieldOne = "stuff"
oneOtherClass.fieldTwo = 3
let aMirror = Mirror(reflecting: oneMyClass)
let bMirror = Mirror(reflecting: oneOtherClass)
for thing in aMirror.children
{
for thing2 in bMirror.children
{
if thing.label! == thing2.label!
{
print("property: \(thing.label!)")
print("before: \(thing.value)")
print("after: \(thing2.value)")
print("")
//let myTest = thing.value == nil ? "nil" : "not nil"
}
}
}
And it generates the following output:
property: fieldOne
before: Optional("blah")
after: Optional("stuff")
property: fieldTwo
before: nil
after: Optional(3)
property: fieldThree
before: Optional(3.5)
after: nil
As you can see, the expected properties are displayed as "nil". However, if you uncomment the let statement, you get an error stating:
playground52.swift:37:38: error: value of type 'Any' (aka 'protocol<>') can never be nil, comparison isn't allowed
And yet, we know from the output that it IS nil. How can this be and what can I do about it?
Based on this answer, I recommend using if case Optional<Any>.some(_).
For example:
aMirror.children.forEach {
guard let propertyName = $0.label else { return }
if case Optional<Any>.some(_) = $0.value {
print("property: \(propertyName) is not nil")
} else {
print("property: \(propertyName) is nil")
}
}
Thats look like some sort of bug. Look at that
let x = childMirror.value == nil ? "Nil" : "Not Nil" //dont compile.
let y = { (value:Any?) in
return value == nil ? "Nil" : "Not Nil"
}
let z = y(childMirror.value) //compile, but doesn't evaluate.
I guess the problem is because Any can store a Optional, but can't be wrapped around one. Try this:
func getValue(unknownValue:Any) -> Any {
let value = Mirror(reflecting: unknownValue)
if value.displayStyle != .Optional || value.children.count != 0 {
return "Not Nil"
} else {
return "Nil"
}
}

How to make string fast enumeration in string in Swift? [duplicate]

This question already has answers here:
Split a String into an array in Swift?
(40 answers)
Closed 6 years ago.
For example i have usual fast enumeration
for (var myChar:Character) in "Hello World!"
{//code }
This works fine and i can do whatever i want with each character of this string.
But what if i want to use string instead of character, like this
for ( var myStr : String) in "Hello World!"//this is error
{
switch myStr
{
case "Hello":
//code
case "World!":
//code
default:
break
}
}
Is it possible to implement this? Thanks
You can use componentsSeparatedByCharactersInSet to divide the string into an array of strings:
import Foundation // not necessary if you import UIKit or Cocoa
for myStr in "Hello World!".componentsSeparatedByCharactersInSet(NSCharacterSet(charactersInString:" ")) {
switch myStr {
case "Hello":
println("well hello there")
case "World!":
println("the whole world")
default:
println("something else")
}
}
In place of NSCharacterSet(charactersInString:" ") can also use NSCharacterSet.whitespaceCharacterSet() or NSCharacterSet.whitespaceAndnewlineCharacterSet() depending on what kinds of characters divide your words.
If your words are separated by a single space, you can use the shorter:
for myStr in "Hello World!".componentsSeparatedByString(" ") {
...
}
You cannot just enumeratate by strings over a string. you need to tell what ranges the substring has to have.
Here it is done by words:
var str:String = "Hello World!"
str.enumerateSubstringsInRange(Range<String.Index>(start:str.startIndex , end: str.endIndex), options: NSStringEnumerationOptions.ByWords) { (substring, substringRange, enclosingRange, stop) -> () in
switch substring
{
case "Hello":
println("Hi")
case "World":
println("universe")
default:
break
}
}
but actually I am cheating. In you code you want to switch for World!, but I am using World. I do this as in word-based enumeration non-alphanumeric characters are ignored.
But we have all information to fix it
var str:String = "Hello World!"
str.enumerateSubstringsInRange(Range<String.Index>(start:str.startIndex , end: str.endIndex), options: NSStringEnumerationOptions.ByWords) { (substring, substringRange, enclosingRange, stop) -> () in
var enclosingStr = str.substringWithRange(enclosingRange)
enclosingStr = enclosingStr.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet())
switch enclosingStr
{
case "Hello":
println("Hi")
case "World!":
println("universe")
default:
break
}
}
While in Swift 2.0, I use
let line = "Hello, world"
for (index, value) in line.characters.enumerate() {
// do something
}

What's wrong with my code that tries to check the type of a variable? [duplicate]

This question already has answers here:
How to determine the type of a variable in Swift
(5 answers)
Closed 8 years ago.
What's wrong with my code that tries to check the type of a variable?
The following code produces error that says "'is' test is always true". Note that I don't want to set p to a value because it could be nil, hence the use of optional.
import Foundation
var p:String?
if p as String? {
println("p is a string type")
}
else {
println("p is not a string type")
}
Now if I test against String type, it won't even compile:
import Foundation
var p:String?
if p as String {
println("p is a string type")
}
else {
println("p is not a string type")
}
Is this a compiler bug? If not what did I do wrong?
Adding on to the answers that revolve around optional binding, there is a more direct way that Apple provides.
The is operator exists exactly for this purpose. However, it doesn't allow you to test trivial cases but rather for subclasses.
You can use is like this:
let a : Any = "string"
if a is String {
println("yes")
}
else {
println("no")
}
As expected, that prints yes.
You already know that p is an optional string. You don't need to convert it to a type, you can simply do Optional Binding:
if let aString = p {
println("p is a string: \(aString)")
}
else {
println("p is nil")
}
Normally you check if a variable is of a certain type using the as? operator:
var something : AnyObject = "Hello"
if let aString = something as? String {
println("something is a string: \(aString)")
}
but you do not use that mechanism when checking if an optional is nil.
This will also work if your object is an optional:
var something : AnyObject? = "Hello"
if let aString = something as? String {
println("something is a string: \(aString)")
}
Since p is an optional String, you can use it in your conditional test like so:
import Foundation
var p: String?
if p {
println("p has been assigned a String value")
}
else {
println("p is nil")
}
If p has been assigned a String value and you would like to use that value in the body of your if statement, then you can use 'optional binding' to assign its value to a local constant you can work with:
if let pValue = p {
println("p is assigned \(pValue)")
}
else {
println("p is nil")
}