Is there an Object class in Swift?
As explained in "Why is there no universal base class in Swift?", no, but there is a common protocol that every type implicitly conforms to: Any
.
// A statically typed `Any` constant, that points to a value which
// has a runtime type of `Int`
let something: Any = 5
// An array of `Any` things
let things: [Any] = [1, "string", false]
for thing in things {
switch thing {
case let i as Int: consumeInt(i)
case let s as String: consumeString(s)
case let b as Bool: consumeBool(b)
// Because `Any` really does mean ANY type, the compiler can't prove
// that this switch is exhaustive, unless we have a `default`
default: fatalError("Got an unexpected type!")
}
}
However, using Any
is ill-advised most of the time. For most purposes, discriminated unions are a better choice, which Swift has in the form of enums. These ensure that all possible types are considered:
// Using an enum with associated values creates a discriminated union
// containing the exact set of type that we wish to support, rather than `Any`
enum SomeValue { // Note: this is a bad name, but just as an example!
case int(Int)
case string(String)
case bool(Bool)
}
let someValues: [SomeValue] = [.int(1), .string("string"), .bool(false)]
for value in someValues {
switch value {
case .int(let i): consumeInt(i)
case .string(let s): consumeString(s)
case .bool(let b): consumeBool(b)
// Enums have finitely many cases, all of which we exhausted here
// No `default` case required!
}
}
iOS: create an object class with Swift
This is not actually an answer (see other answers for a solution, such as @Greg's and @zelib's), but an attempt to fix some mistakes I see in your code
No need to create computed + stored property (unless you have a reason for that):
class City: NSObject {
var name: String = ""
}If you inherit from
NSObject
, you automatically lose all swift features - avoid it (unless you have a reason for that)class City {
var name: String = ""
}You are using an empty string as absence of value - swift provides optionals for that
class City {
var name: String?
}Alternative to 3., a city without a name wouldn't make much sense, so you probably want each instance to have a name. Use non optional property and an initializer:
class City {
var name: String
init(name: String) {
self.name = name
}
}Avoid implicitly unwrapped optionals (unless you have a reason for that):
var city: City
How do you find out the type of an object (in Swift)?
Swift 3 version:
type(of: yourObject)
What is the equivalent of Java Object in Swift?
As I understand you want "caller" to be any type you want.
In this case you need to use "AnyObject" type here.
Documentation
Using Swift object class in Objective-C
Try this:
@objcMembers
class SaveFile: NSObject {//<-NSObject, not NSOBject
var name: String?
var location: String?
init(id: String, size: String) {
super.init()
//other code
}
}
When you write a class which is used in Objective-C code, it's an easy way to annotate with @objcMembers
.
Or else, you can annotate all properties and methods including initializers with @objc
:
class SaveFile: NSObject {
@objc var name: String?
@objc var location: String?
//@objc(initWithId:size:) do work
@objc init(id: String, size: String) {
super.init()
//other code
}
}
Store a custom object (class in Swift) for access by an Objective-C method
Go to your project’s general settings. Select the proper target for your app. Go to “Build Settings” and switch to “All”, instead of “Basic” which is the default. Here search for the “Packaging” section. Turn on “Defines Module”, by changing “No” to “Yes”.
When this is turned on we will now be able to use swift classes inside
of objective-c files.
Before leaving the “Build Settings” look for “Product Module Name” in the “Packaging” section. This will be important so make sure to take note of and copy the “Product Module Name” exactly.
Next go to an objective-c class where you would like to be able to have access to your swift class. In the implementation or .m file of this class import a header like this:
#import "MyProjectModuleName-Swift.h"
Here the file name of the import must be the exact Project Module Name from the build settings. Any objective-c file where you want access to your swift class should include this import.
- Now it is worth mentioning one potential issue that may arise when using a swift class. Objective-c cannot read top-level swift classes. So if you go to use a method or variable from your swift class directly it will not be recognized. There are one simple solution to this issue. It’s to make your class
public
@objc public class myClass
Turning Java object class into Swift class
The main issue here is that your java class is poorly designed and you are taking this design with you when writing it in swift. Rather than having a bunch of properties that are collections you should create a struct for those properties and have one array with the struct. (I didn't include all properties to keep the code shorter).
struct Firework {
var category: Int
var name: String
var shotCount: String
var price: String
var special: Bool
}
and then declare it in the main class
class FireworkList {
private var fireworks = [Firework]()
Below is the class with the add
, count
and categorySort
functions to show some examples of how to use this struct. As you can see this means much less code. I also taken the liberty to rename properties and functions to follow recommended swift naming practices.
For the categorySort
I have made use of the high order function filter
to collect the correct items. If you are going to work with swift I would recommend you learn more about it and the other high order functions like sort
, map
etc.
Also worth mentioning to someone coming from java is that we don't use get/set methods to the same extent in swift. We most access the property directly like let x = myObject.someValue
or myObject.someValue = 10
class FireworkList {
var fireworks = [Firework]()
private let specialCategoryNumber = 15
func add(cat : Int, name : String, shot : String, price : String, special: Bool) {
self.fireworks.append(Firework(category: cat, name: name, shotCount: shot, price: price, special: special))
}
func count() -> Int { return fireworks.count }
func categorySort(position : Int) -> [Firework] {
switch position {
case 0:
return self.fireworks
case specialCategoryNumber:
return self.fireworks.filter { $0.category == specialCategoryNumber && $0.special}
default:
return self.fireworks.filter {$0.category == position}
}
}
}
Swift 3: How to *specify* class of object, ruling out parent memberships?
You can use something like:
if type(of: self) == Parent.self {
// this only runs for exact type matches, not subclasses
}
That checks for equality of the types rather than polymorphic conformance of the instance (i.e. self is Parent
)
Related Topics
Swift Protocol That Is Using an Enum with Generic Associated Type
Implement a Custom Staggeregrid in UIview Like Etsy App in Swift
iOS Coredata Compatible with Both iOS 9 and iOS 10
Validatemenuitem or Menuwillopen Not Called for Nsmenu
How to Constrain Second Nsviewcontroller Minimum Size in Os X App
Realm Data Insertion Took Over 7Mins for Big Size JSON
Swift: How to Update UI When Listening to a Stream
Saving a Screen Recording with Rpscreenrecorder Start Capture
Add Accessory to Home Always Returns Error(Genericerror)
Does Cidetector for Other Barcode Types
How to Assign Elements of a Dictionary to JSON Object in Vapor 3
Access Safari Bookmarks in Macos Mojave Programmatically
Msmessagelivelayout Freeze/Crash in Transcript When Info.Plist Contains Privacy Request
How to Create a UIprintpaper to Test UIprintinteractioncontrollerdelegate
Issues with Uploading from Xcode 9 to App Store/ Itunes Connect