How to Retrieve the Type of an Object in Swift

How do you find out the type of an object (in Swift)?

Swift 3 version:

type(of: yourObject)

How to get the object type in Swift3

Expanding on @jglasse's answer, you can get the type of an object by using

let theType = type(of: someObject)

You can then get a string from that by

let typeString = String(describing: type)

Or in one line:

let typeString = String(describing: type(of: someObject))

how to get some data from the type any in swift

This is the string format you would get for an NSData. Assuming it really is an NSData, you would convert it to a Data. (And then, ideally, replace Any with Data in your definition. Any types a major pain to work with.)

if let data = machineNumber as? Data {
// use `data` for the bytes
}

Get element.type from generic object in swift

Maybe problem in line

let allUploadingObjects = realm.objects(T.self())

It should be:

let allUploadingObjects = realm.objects(T.self) // removed needles parentheses

How to build a Swift object that can control the mutability of its stored properties

import Foundation

protocol PropertyWrapperWithLockableObject {
var enclosingObject: LockableObjectBase! {get set}
}

@propertyWrapper
class Lockable<Value>: PropertyWrapperWithLockableObject {
private var _wrappedValue: Value
var enclosingObject: LockableObjectBase!

init (wrappedValue: Value) { self._wrappedValue = wrappedValue }

var wrappedValue: Value {
get {
precondition(enclosingObject.isLocked, "Cannot access object properties until object is locked")
return _wrappedValue
}
set {
precondition(!enclosingObject.isLocked, "Cannot modify object properties after object is locked")
_wrappedValue = newValue
}
}
}

class LockableObjectBase {
internal var isLocked: Bool = false {
didSet { isLocked = true }
}

init () {
let mirror = Mirror(reflecting: self)
for child in mirror.children {
if var child = child.value as? PropertyWrapperWithLockableObject {
child.enclosingObject = self
}
}
}
}

Usage:

class DataObject: LockableObjectBase {
@Lockable var someString: String = "Zork"
@Lockable var someInt: Int

override init() {
someInt = 42
// super.init() // Not needed in this particular example.
}
}

var testObject = DataObject()
testObject.isLocked = true
print(testObject.someInt, testObject.someString) // 42, Zork
testObject.isLocked = false // Has no effect: Object remained locked
print (testObject.isLocked) // true
testObject.someInt = 2 // Aborts the program

arsenius's answer here provided the vital reflection clue!



Related Topics



Leave a reply



Submit