I'm trying to do the equivalent in Objective-C:
if (causeStr != nil) {
...
}
I would get a compiler error if do this:
if !(let myString = causeStr) {
}
So I'm left with this:
if let myString = causeStr {
} else {
// ... do something
}
Is there a more-elegant way to do this?
Yes, there's a more elegant way, and coincidentally it's the same as in obj-c:
if myString == nil {
...
}
Note: Your 1st snippet of code should be:
if (causeStr == nil) {
...
}
otherwise it means I misunderstood your question...
Related
I've made extension
extension Optional where Wrapped == [Any] {
var isNilOrEmpty: Bool {
get {
if let array = self {
return array.count == 0
} else {
return false
}
}
}
}
Then I try to use it like this
if fetchedResults.fetchedObjects.isNilOrEmpty { ... }
I'm getting error
'[Task]?' is not convertible to 'Optional<[Any]>'
But, by specification
Any can represent an instance of any type at all, including function types.
What is my mistake here?
Task is subclass of NSManagedObject if it matters.
Well, [Task] and [Any] are two different types, and Wrapped == [Any] won't work.
Proper way would be to limit Wrapped by protocol, not specific type.
extension Optional where Wrapped: Collection {
var isNilOrEmpty: Bool {
get { // `get` can be omitted here, btw
if let collection = self {
return collection.isEmpty // Prefer `isEmpty` over `.count == 0`
} else {
return true // If it's `nil` it should return `true` too
}
}
}
}
I want to create an array of weak referenced delegates like so...
fileprivate class WeakDelegate<T:AnyObject> {
weak var value:T?
init (value:T) {
self.value = value
}
}
class Radio {
private var delegates = [WeakDelegate<AnyObject>]()
}
So far so good...? what I'd like to do also is tidy up my array in these two ways...
1.
func removeDeadDelegates() {
let liveDelegates = delegates.filter { $0.value != nil }
delegates = liveDelegates
}
and 2.
func remove<T>(specificDelegate:T) {
let filteredDelegates = delegates.filter { $0.value != specificDelegate }
listeners = filteredDelegates
}
Says Cannot convert value of type 'T' to expected argument type '_OptionalNilComparisonType'
Now I can just add this to make the warning go away like this...
let liveDelegates = delegates.filter {
if let d = specificDelegate as? _OptionalNilComparisonType {
return $0.value != d
}
return true
}
but this cast doesn't work...
I'm concerned because I'm not sure what this means... can anyone explain why I can't compare generics with == and why this cast is failing?
Thanks for your time
EDIT
Like this?
func remove<T:AnyObject>(delegate:T) {
let filteredDelegates = delegates.filter { $0.value != delegate }
delegates = filteredDelegates
}
No joy sadly...
Instances of a class type can be compared with the “identical to”
=== and “not identical to” !== operators:
func remove(specificDelegate: AnyObject) {
let filteredDelegates = delegates.filter { $0.value !== specificDelegate }
delegates = filteredDelegates
}
The same works for a generic method
func remove<T:AnyObject>(specificDelegate: T) {
let filteredDelegates = delegates.filter { $0.value !== specificDelegate }
delegates = filteredDelegates
}
(but I do not yet see the advantage of doing so).
This question already has answers here:
Variable used before being initialized in function
(6 answers)
Closed 5 years ago.
I have this code :
public class Foo {
init?() {
do {
let sd = FileManager.default.temporaryDirectory.appendingPathComponent("bar")
let ressourceValues = try sd.resourceValues(forKeys: [.isDirectoryKey])
if let isDirectory = ressourceValues.isDirectory {
if isDirectory {
self.something = sd
} else {
return nil
}
} else {
try FileManager.default.createDirectory(atPath: sd.path, withIntermediateDirectories: false, attributes: nil)
}
} catch {
return nil
}
}
public static let `default`: Foo? = Foo()
var something: URL
}
I get this error on the init? line:
Variable 'self.something' used before being initialized
And yet I don't see any place where I am using it in the initialiser.
What's wrong ?
Thank you
Since something isn't optional you must initialize it with a non-nil value. Your init may succeed without initializing something.
I have a little bit misunderstanding how to use -(void) in swift correctly. Whenever I have tried to write a code using -(Void) but I am getting an error "Expected declaration" or sometimes "Binary operator '-' cannot be applied to operands of type 'UIFont' and '(Void).Type'".
Why is this happening? What is the right way to use this functionality correctly in swift?
{
- (Void)keyboardWillShow { //>> showing me the error "Binary operator '-' cannot be applied to operands of type 'UIFont' and '(Void).Type'"
// Animate the current view out of the way
if (self.view.frame.origin.y >= 0)
{
[self setViewMovedUp:YES];
}
else if (self.view.frame.origin.y < 0)
{
[self setViewMovedUp:NO];
}
}
}
Thanks
It sounds like you're trying to declare a function with no return value. In Swift this is done as:
func thisFunction() {
..
}
You can return nil value like below code:
func myFunc(myVar: String) -> ()? {
print(myVar)
return nil
}
var c = myFunc("Hello")
print(c) // nil
but Swift Function always return default value nil if not declared. like below code:
func myFunc(myVar: String) {
print(myVar)
return
}
var c = myFunc("Hello")
print(c) // ()
Having difficulty, ound some articles / questions asking this but it wasn't exactly what it was.
var catMoves = 0
let maxCatMoves = 8
func catOutOfMoves() {
if catMoves = maxCatMoves {
var aliveCat = 0
}} //do something
else {//do something else}
Thanks, much appreciated.
Your if statement is not closed properly
func catOutOfMoves() {
if catMoves = maxCatMoves {
var aliveCat = 0
//do something
}
else {
//do something else
}
}