Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

RJSwiftMacros is a Swift package that provides swift macros

License

NotificationsYou must be signed in to change notification settings

rezojoglidze/RJSwiftMacros

Repository files navigation

RJSwiftMacros is a Swift package that provides macros.

Tip

All macros are used in SwiftUIDemo project. see theLINK.

Macros

Warning

MockBuilder macro doesn't work atSwiftUI#Preview macro. Here is asolution.

MockBuilder

  • MockBuilder(numberOfItems: Int): Generates a mock instance and an array of mock data based on your model.
  • MockBuilder hasMockBuilderProperty member macro, with which you can set the initial value to the desired property.
Key Features:
  • Default Usage:@MockBuilder() generates a one single mock instance.
  • Customizable: You can also specify parameter likenumberOfItems if you need to have array of mock items.

MockBuilderProperty macro

  • MockBuilderProperty<T: Any>(value: T): Sets an initial value to a property within a struct or class.

CodingKeys

  • CodingKeys(codingKeyType: CodingKeyType): Automatically generatesCodingKeys for a struct based on the specifiedCodingKeyType which has two cases:.camelCase and.snakeCase.
  • CodingKeyProperty(:_): Allows you to adjust the coding key for a specific property.
  • CodingKeyIgnored(): Allows you to exclude specific properties from the coding process when using theCodingKeys macro.

Installation

Swift Package Manager

To depend onRJSwiftMacros in a SwiftPM package, add the following to your Package.swift.

dependencies:[.package(url:"https://github.com/rezojoglidze/RJSwiftMacros", from:"<#latest RJSwiftMacros tag#>"),],

To addRJSwiftMacros as a dependency of your Xcode project, go to the Package Dependencies tab of your Xcode project, click the plus button and search forhttps://github.com/rezojoglidze/RJSwiftMacros

Usage

MockBuilder macro

Import the RJSwiftMacros module and apply the macros to your structs and properties:

Usage ofMockBuilder:Macro generates twostatic properties:mock andmockArray.mockArray count equalsnumberOfItems value. If you want to set a custom value to the desired property, use@MockBuilderProperty macro. If the custom value granted is prohibited you will get a swift standard warning error.image

To generate only.mock value, you can use@MockBuilder() without any param passing.

Important

Type which participating in the mock building should have@MockBuilder() itself. Below example, we want to havelet type: VehicleType mocked version, soVehicleType should have@MockBuilder()

import RJSwiftMacros@MockBuilder(numberOfItems:2)enumVehicleType:String,Decodable{case carcase buscase motorcycle}@MockBuilder()structExampleAllSupportedTypes{letintVariable:Intletint8Variable:Int8letint16Variable:Int16letint32Variable:Int32letint64Variable:Int64letuintVariable:UIntletuint8Variable:UInt8letuint16Variable:UInt16letuint32Variable:UInt32letuint64Variable:UInt64letfloatVariable:Floatletfloat32Variable:Float32letfloat64Variable:Float64letdoubleVariable:DoubleletdecimalVariable:DecimalletnsDecimalNumberVariable:NSDecimalNumberletstringVariable:StringletboolVariable:BoolletdateVariable:DateletuuidVariable:UUIDletcgPointVariable:CGPointletcgRectVariable:CGRectletcgSizeVariable:CGSizeletcgVectorVariable:CGVectorletcgFloatVariable:CGFloatleturlVariable:URLletimageVariable:ImageletcolorVariable:Colorletvehicle:VehicleTypeletavailableTimeSlot:Set<String>letarrayOfString:[String]letclosureVariable:()->Voidlettuples:((String,String,Int),Bool?)letpassthroughSubject:PassthroughSubject<Bool,Never>letcurrentValueSubject:CurrentValueSubject<Void,Never>}#if DEBUGpublicstaticvarmock:ExampleAllSupportedTypes{.init(           intVariable:54248,           int8Variable:92,           int16Variable:17693,           int32Variable:1748550107,           int64Variable:85105,           uintVariable:75340,           uint8Variable:221,           uint16Variable:6060,           uint32Variable:34678,           uint64Variable:4145,           floatVariable:38105.523,           float32Variable:99252.86,           float64Variable:57161.44399989151,           doubleVariable:45860.372174783995,           decimalVariable:80414.91669166147584,           nsDecimalNumberVariable:57109.7344805794816,           stringVariable:"Lorem ipsum dolor sit amet",           boolVariable:false,           dateVariable:Date(timeInterval:77349, since:Date()),           uuidVariable:UUID(),           cgPointVariable:CGPoint(),           cgRectVariable:CGRect(),           cgSizeVariable:CGSize(),           cgVectorVariable:CGVector(),           cgFloatVariable:CGFloat(),           urlVariable:URL(string:"https://www.tiktok.com")!,           imageVariable:Image(systemName:"swift"),           colorVariable:Color.primary.opacity(0.6),           vehicle:VehicleType.mock,           availableTimeSlot:Set<String>(),           arrayOfString:["in voluptate velit esse cillum dolore"]"Duis aute irure dolor in reprehenderit","Excepteur sint occaecat cupidatat non proident","sed do eiusmod tempor incididunt",],           closureVariable:{},           tuples:(("Duis ac tellus et risus vulputate vehicula","Duis aute irure dolor in reprehenderit",42372),false),           passthroughSubject:PassthroughSubject<Bool,Never>(),           currentValueSubject:CurrentValueSubject<Void,Never>(()))}#endif}

To generate both.mock and.mockArray properties use@MockBuilder(numberOfItems: 2).numberOfItems is equal to the count of mock array.

import RJSwiftMacros@MockBuilder(numberOfItems:2)structPerson{letname:String?letsurname:[String]?@MockBuilderProperty(value:Color.blue)letcolor:Color?@MockBuilderProperty(value:Image(systemName:"swift"))letimage:Image?@MockBuilderProperty(value:"k")letcharacter:Character#if DEBUGstaticvarmock:Person{.init(            name:"Lorna,            surname: ["Clare"],            color:Color.blue.opacity(0.6),            image:Image(systemName:"swift"),            character:"k")}staticvarmockArray:[Person]{[.init(               name:"Valentina,               surname: ["Queenie"],               color:Color.blue.opacity(0.6),               image:Image(systemName:"swift"),               character:"k"),.init(               name:"Lorna,               surname: ["Bettye"],               color:Color.blue.opacity(0.6),               image:Image(systemName:"swift"),               character:"k")]}#endif}

CodingKeys macro

Usage ofCodingKeys withoutcodingKeyType param passing generates CodingKeys with.camelCase.CodingKeys macro works only with stored property types. If you want to set custom coding key to the desired param, use@CodingKeyProperty(desired_value). To ignore desired param fromCodingKeys enum, use@CodingKeyIgnored().

import RJSwiftMacros@CodingKeys()classCar{letmodelColor:String@CodingKeyProperty("car_model")letmodel:String@CodingKeyIgnored()letspeed:Intinit(modelColor:String, model:String, speed:Int){self.modelColor= modelColorself.model= modelself.speed= speed}enumCodingKeys:String,CodingKey{case modelColorcase model="car_model"}}

CodingKeys generation with.snakeCase.

import RJSwiftMacros@CodingKeys(codingKeyType:.snakeCase)structUniversity{letname:StringletstudentCapacity:Intletcars:[String]?varclosure:(()->())?staticvarstudents:[String]=[]varoldName:String{"Tbilisi"}enumCodingKeys:String,CodingKey{case name="name"case studentCapacity="student_capacity"case cars="cars"}}

Requirements

  • Swift 5.10 or later
  • macOS 10.15 or later
  • iOS 15 or later

Contributing

Contributions are welcome! Please open an issue or submit a pull request on GitHub.

Contact

For questions or feedback, feel free to reach out torezojoglidze7@gmail.com.


[8]ページ先頭

©2009-2025 Movatter.jp