Swift runtime documentation
This documentation hasn't been released, and nobody outside of Apple knows if it ever will.
Since the ObjC runtime is available on opensource.apple.com, I would imagine that the Swift runtime library source will be made available once Yosemite becomes public.
How to detect in runtime that app uses swift
Please find below the possible approach based on public documented dyld
API available since iPhone2 and valid for all modern iOS versions. And libswiftCore.dylib
is present always for swift.
Taking into account that Swift might be in some application plug-ins, the below function should be called regularly (or at least till first positive result) on your framework API call.
#import <mach-o/dyld.h>
BOOL isSwiftLoaded() {
return NSVersionOfRunTimeLibrary("libswiftCore.dylib") != -1;
// -1 is documented indicator that library is not loaded
}
Swift function swizzling / runtime
I've succeed with method swizzling in Swift. This example shows how to hook description method on NSDictionary
My implementation:
extension NSDictionary {
func myDescription() -> String!{
println("Description hooked")
return "Hooooked " + myDescription();
}
}
Swizzling code:
func swizzleEmAll() {
var dict:NSDictionary = ["SuperSecret": kSecValueRef]
var method: Method = class_getInstanceMethod(object_getClass(dict), Selector.convertFromStringLiteral("description"))
println(dict.description) // Check original description
var swizzledMethod: Method = class_getInstanceMethod(object_getClass(dict), Selector.convertFromStringLiteral("myDescription"))
method_exchangeImplementations(method, swizzledMethod)
println(dict.description) //Check that swizzling works
}
Edited:
This code will work for any custom Swift class that inherits from NSObject (but will not work for classes that don't.) More examples - https://github.com/mbazaliy/MBSwizzler
Swift: obtain module at runtime?
Riffing off of @CouchDeveloper's excellent answer, you can get the module name for an arbitrary Swift type. You can use this to get the module name of any arbitrary code, by creating a type for this purpose.
func moduleName(for type: Any.Type) -> String {
// parse module name from string that looks like "ModuleName.ClassName"
if let subSequence = String(reflecting: type.self).split(separator: ".").first {
return String(subSequence)
} else {
return ""
}
}
print(moduleName(for: String.self)) // -> Swift
enum Test {}
print(moduleName(for: Test.self)) // -> SwiftModuleNameExample
This can even be embedded into a protocol.
public protocol Module {}
extension Module {
static var name: String { moduleName(for: Self.self) }
}
class ThisModule: Module {}
print(ThisModule.name) // -> SwiftModuleNameExample
A macOS command-line Xcode project for this code lives here.
INIntent `setImage` make runtime crash in Swift 5
As far as I checked...
The two methods are available in Objective-C.
- imageForParameterNamed:
- setImage:forParameterNamed:
And the generated interface for these methods shown as...
// Set an image associated with a parameter on the receiver. This image will be used in display of the receiver throughout the system.
@available(iOS 12.0, *)
open func __setImage(_ image: INImage?, forParameterNamed parameterName: String)
@available(iOS 12.0, *)
open func __image(forParameterNamed parameterName: String) -> INImage?
The docs or code suggestion of Xcode will not show you these, but you can use them in Swift 5 code:
intent.__setImage(image, forParameterNamed: "spotName")
Though, using underscore-leaded methods may be taken as using private APIs when submitting your app to App Store.
This sort of things sometimes happens when Apple is swiftifying some methods and not completed yet.
As for now, what you can do are...
Send a bug report to Apple, immediately
Write an Objective-C wrapper for these methods and import it into Swift
or
- Delay submitting your up until new SDK with this issue fixed will be provided
(Can be years...)
How to go about adding a link/reference to another method in documentation Xcode?
This link solved my problem
Particularly, this is how I went about it
Thanks to Oleg for the link
swift: Equivalent objective-c runtime class
First, it's hard to translate that code to Swift without knowing what you used that class object for in Objective-C.
In Objective-C, class objects are objects, and the type Class
can hold a pointer to any class object. However, when Objective-C APIs are bridged to Swift, the type Class
is converted to AnyClass!
in Swift, where AnyClass
is defined as AnyObject.Type
. Types in Swift are not objects, and thus are not directly equivalent to class objects in Objective-C. However, if you intend to use an Objective-C API from Swift, it will have been bridged to expect AnyClass
anyway, so you have to pass a type. You can get the type of any expression using .dynamicType
; for example:
self.dynamicType
(If you really want to get the class object as an Swift object the same way as in Objective-C, and not as a Swift type, there are some convoluted ways to do that too.)
However, your description of your problem reveals another issue. If you just want to get the type of an object, and self
is an object, then var klass: AnyClass = object_getClass(self)
should have worked, since object_getClass()
takes an AnyObject
and returns an AnyClass
. The only explanation for it not working is if self
is not an object. Your error message reveals that, indeed, self
is a type, not an object.
self
is a type if this code is running in a class method. You should have really given context for your code (obviously, you didn't put Class class = [self class];
at the top level of a file), because taken out of context it's easy to misunderstand. In Objective-C Cocoa, there are two very different methods named class
: an instance method, -class
, which returns the class of the object, and a class method, +class
, which simply returns the (class) object it's called on. Since your code is in a class method, in Objective-C, self
points to a class object, and [self class]
runs the class method +class
, which just returns the object it's called on. In other words, [self class]
is exactly identical to self
. You should have just written self
all along, but didn't realize it.
So the answer is that the Objective-C should have been
Class class = self;
and similarly the Swift should be
var klass: AnyClass = self
IOS-SWIFT- How to resolve the warning from the Apple Documentation Code about KVO? Why Xcode auto correction introduced an error?
The code snippets in Apples documentation are for example only - that's not a complete implementation.
Presumably, you will be doing something else with observer
, at which point you will no longer get the "not used" warnings.
Sample usage (just for demonstration, not to be considered production code):
class ExampleViewController: UIViewController {
var observed: MyObjectToObserve!
var observer: MyObserver!
override func viewDidLoad() {
super.viewDidLoad()
observed = MyObjectToObserve()
observer = MyObserver(object: observed)
}
@IBAction func didTap(_ sender: Any) {
observed.updateDate()
}
}
Create a new view controller; set its class to ExampleViewController
; add a button and connect it to @IBAction func didTap
.
Run the app.. each time you tap the button, you will see the print()
output in the debug console.
Related Topics
Ckcontainer.Discoverallidentities Always Fails
Swiftui - Pass Data to Different Views
Can a Subclass Override a Function and Make More Restrictive Return
Create Spotlight-Like Window in Swift 4
How to Implement Default Associated Values with Swift Enums
App Crashes from IPA File But Runs Fine from Xcode
Xcode UI Test:Accessibility Query Fail on Uitableviewcell
How to Convert Tuple to Anyobject in Swift
What Does This Two Question Mark Mean
Self Refrence Inside Swift Closure Return Nil Some Time
What Is the Markup Format for Documentation on the Parameters of a Block in Swift
iOS 13, Custom Image, Title and Subtitle in the Presented Uiactivityviewcontroller
How to Call a Generic Swift Function When None of the Arguments Provides the Generic Type
How to Get a Double Value Up to 2 Decimal Places
Why Do I Get "Static Member '...' Cannot Be Used on Instance of Type '...'" Error
How to Subclass a Class Which Doesn't Have Any Designated Initializers