Can you really name any Objective-C method for AnyObject?

According to the “Using Swift with Cocoa and Objective-C” iBook (near Loc 9) regarding idcompatibility:

You can also call any Objective-C method and access any property without casting for a more specific type of class.

The example given in the book (shown below) does not compile, which, apparently, contradicts the statement above. According to this book, the last line below should not be executed because the property lengthdoes not exist in the object NSDate.

var myObject: AnyObject = UITableViewCell()
myObject = NSDate()
let myLength = myObject.length?

Instead, it cannot be compiled with "Could not find overload for" length ", which takes the arguments" set arguments "in the last line.

Is this an error, typo, or statement about invoking an Objective-C method that is incorrect?

+4
source share
1 answer

a compiler error says that lengththis is a function and you call it with the wrong arguments

you can do myObject.length?()that returnnil

myObject.count?will also give you nila compilation error free

 xcrun swift
Welcome to Swift!  Type :help for assistance.
  1> import Cocoa
  2> var obj : AnyObject = NSDate()
obj: __NSDate = 2014-06-25 13:02:43 NZST
  3> obj.length?()
$R5: Int? = nil
  4> obj.count?
$R6: Int? = nil
  5> obj = NSArray()
  6> obj.length?()
$R8: Int? = nil
  7> obj.count?
$R9: Int? = 0
  8>

I think that the compiler was looking for all the methods and properties that called length, it found that some class provides length(), but the class does not provide length, therefore, an error message. Just like when you call [obj nonexistmethod]in ObjC, the compiler will give your error saying that it nonexistmethoddoesn’t exist, even you call it on idan object like

, , Swift

 14> obj.notexist?
<REPL>:14:1: error: 'AnyObject' does not have a member named 'notexist'
obj.notexist?
^   ~~~~~~~~

 14> obj.notexist?()

<REPL>:14:1: error: 'AnyObject' does not have a member named 'notexist()'
obj.notexist?()
^   ~~~~~~~~
+1

Source: https://habr.com/ru/post/1545922/


All Articles