lang
stringclasses 10
values | seed
stringlengths 5
2.12k
|
---|---|
swift | private static let g15BCHDigit = bchDigit(of: g15)
private static let g18BCHDigit = bchDigit(of: g18)
static func bchTypeInfo(of data: Int) -> Int {
var d = data << 10
while bchDigit(of: d) - g15BCHDigit >= 0 {
d ^= (g15 << (bchDigit(of: d) - g15BCHDigit))
}
return ((data << 10) | d) ^ g15Mask
} |
swift | //
// Code generated by Microsoft (R) AutoRest Code Generator.
public enum RollingUpgradeStatusCodeEnum: String, Codable
{
// Cancelled specifies the cancelled state for rolling upgrade status code.
case Cancelled = "Cancelled"
// Completed specifies the completed state for rolling upgrade status code.
case Completed = "Completed"
// Faulted specifies the faulted state for rolling upgrade status code.
case Faulted = "Faulted"
|
swift | ]
private enum Operation {
case Constant(Double)
case UnaryOperation((Double) -> Double)
case BinaryOperation((Double, Double) -> Double)
case Equals
}
func performOperation(symbol: String) {
if let operation = operations[symbol] {
switch operation { |
swift | // Created by Ramunas Jurgilas on 2018-05-03.
// Copyright © 2018 Ramūnas Jurgilas. All rights reserved.
//
import Foundation
extension Forecast {
var localizedTemperature: String {
get {
return low
//high
}
}
} |
swift |
return self.mapReduce(mapper: mapper, reducer: reducer, flows: flows)
}
public func histogram() -> [Element: Int] {
return self.reduce(into: [:]) { counts, elem in counts[elem, default: 0] += 1 } |
swift |
输入: 2->1->3->5->6->4->7->NULL
输出: 2->3->6->7->1->5->4->NULL
https://leetcode-cn.com/problems/odd-even-linked-list/
时间复杂度: O(n) 。总共有 nn 个节点,我们每个遍历一次。
空间复杂度: O(1) 。我们只需要 4 个指针。
解法:分别构造两个奇偶链表,遍历到尾部,然后连接奇数链表到尾和偶数链表到头
**/
func oddEvenList(_ head: ListNode<Int>?) -> ListNode<Int>? {
|
swift | open override var frame: CGRect {
didSet {
backgroundColor = .clear
drawsBackground = true
}
}
}
struct ContentView: View { |
swift | struct Step {
let o1: Tensor<Float>
let o2: Tensor<Float>
let a: Tensor<Int32>
let r: Tensor<Float>
let d: Tensor<Bool>
}
let steps: [Step] |
swift |
updateCounts()
}
func updateCounts() {
errorsCount.stringValue = "\(workbench?.diagnostics(severity: .error).values.flatMap{$0}.count ?? 0)"
warningsCount.stringValue = "\(workbench?.diagnostics(severity: .warning).values.flatMap{$0}.count ?? 0)"
errorsCount.sizeToFit()
warningsCount.sizeToFit()
let width = errorsCount.frame.size.width + warningsCount.frame.size.width + 65
self.view.setFrameSize(NSSize(width: width, height: self.view.frame.size.height))
self.view.invalidateIntrinsicContentSize()
} |
swift | // Dispose of any resources that can be recreated.
}
private func notifications() {
let viewModel = NotificationsViewModel()
let controller = ListViewController(viewModel: viewModel)
navigationController?.pushViewController(controller, animated: true)
}
}
extension ProfileViewController: UITableViewDelegate, UITableViewDataSource {
func numberOfSections(in tableView: UITableView) -> Int {
return 2 |
swift | }
fileprivate lazy var applicationServices : [AFSApplicationDelegateService] = {
return self.obtainServices()
}()
open override func responds(to aSelector: Selector!) -> Bool { |
swift |
/// 计算字符串在指定宽度下的高度值
/// - Parameters:
/// - width: 指定的字符串宽度
/// - font: 字符串使用的字体
/// - options: 字符串绘制选项
/// - attributes: 字符串富文本属性,如果 attributes 中指定了 font,则忽略前面的 font 参数 |
swift | public enum RiotAccountMethods {
case ByPuuid(puuid: SummonerPuuid)
case ByRiotId(riotId: RiotId)
case ActiveShardsByGame(puuid: SummonerPuuid, game: ShardGame)
}
|
swift | .foregroundColor(.neonGreen)
.font(.body).foregroundColor(Color.white)
.padding([.top, .bottom, .trailing, .leading], 40)
.shadow(radius: 10.0, x: 20, y: 10)
VStack(alignment: .leading, spacing: 15) {
Button(action: {
loggedIn.toggle()
}) { |
swift | }
func testExample() throws {
// This is an example of a functional test case.
// Use XCTAssert and related functions to verify your tests produce the correct results.
}
func testPerformanceExample() throws {
// This is an example of a performance test case.
self.measure {
// Put the code you want to measure the time of here.
}
} |
swift |
class MasterSplitViewController: UISplitViewController {
// Override this value so that the status bar style correctly updates when the theme changes
override var preferredStatusBarStyle: UIStatusBarStyle { |
swift | call.reject("The 'type' param is required")
return;
}
let decodedData = NSData(base64Encoded: base64, options: [])
if let data = decodedData {
let decodedimage = UIImage(data: data as Data)
if(decodedimage != nil) {
UIImageWriteToSavedPhotosAlbum(decodedimage!, self, nil, nil)
}
} else {
call.reject("Error with decodedData")
return;
}
|
swift | //
// ServicesResponseHandler.swift
// LinioMVVM
//
// Created by Miguel De León Palacios on 8/30/19.
// Copyright © 2019 MiguelPalacios. All rights reserved.
//
|
swift | }
private func provideSeriesWireframe() -> SeriesWireframe {
return SeriesWireframe()
}
|
swift | if let songsByArtist = songsByArtist, let songsByAlbumArtist = songsByAlbumArtist {
return songsByArtist + songsByAlbumArtist
} else if songsByArtist != nil {
return songsByArtist
} else if songsByAlbumArtist != nil { |
swift | var adventureLogTopWindowNode: AdventureLogTopWindowNode?
var isProcessing = false
func setup() {
DataManager.adventureLog.dqSceneType = .adventure_log
self.scene.backgroundColor = .black
self.scene.leftPad.isHidden = false
self.scene.buttonA.isHidden = false
self.scene.buttonB.isHidden = false
let adventureLog1 = UserDefaultsUtil.loadAdventureLog(number: 1) |
swift | override func remoteControlReceived(with event: UIEvent?) {
if let event = event {
if event.type == UIEventType.remoteControl {
switch event.subtype {
case .remoteControlTogglePlayPause:
if self.player.isPlaying() {
|
swift | ]
return HTTPStubsResponse(jsonObject: jsonObject, statusCode: 200, headers: nil)
}
let startJob: ServerSyncJob = .startJob(instanceId: instanceId, token: deviceToken) |
swift | func test_dynamicTableViewModel() {
let dynamicTableViewModel = HygieneRulesInfoViewModel().dynamicTableViewModel
XCTAssertEqual(dynamicTableViewModel.numberOfSection, 2)
XCTAssertEqual(dynamicTableViewModel.section(0).cells.count, 1)
XCTAssertEqual(dynamicTableViewModel.section(1).cells.count, 6)
}
} |
swift | .macOS(.v10_15),
.iOS(.v13)
],
products: [
.library(name: "WKCodable", targets: ["WKCodable"]),
],
targets: [
.target(name: "WKCodable"),
.testTarget(
name: "WKCodableTests",
dependencies: ["WKCodable"]),
]
)
|
swift |
// MARK: - UICollectionViewDataSource
extension PhotosPickerViewController: UICollectionViewDataSource {
|
swift | public func getSourceName() -> String {
if let sourceName = sourceName {
return sourceName
}
if let inputStream = getInputStream() {
return inputStream.getSourceName()
}
return "List"
}
public func setTokenFactory(_ factory: TokenFactory) {
self._factory = factory |
swift | import UIKit
import AlamofireImage
class MovieDetailsViewController: UIViewController {
@IBOutlet weak var backdrop_view: UIImageView!
@IBOutlet weak var poster_view: UIImageView!
@IBOutlet weak var title_label: UILabel!
@IBOutlet weak var synopsis_label: UILabel!
|
swift | }
func testPerformanceExample() {
// This is an example of a performance test case.
self.measureBlock {
// Put the code you want to measure the time of here.
}
}
|
swift | for attrs in arr! {
// cell的中心点x 和 collectionView最中心点的x值 的间距
let delta = abs(attrs.center.x - centerX)
// 根据间距值 计算 cell的缩放比例
let scale = 1 - delta / (collectionView?.frame.size.width)!
// 设置缩放比例
attrs.transform = CGAffineTransform.init(scaleX: scale, y: scale)
}
return arr
} |
swift | super.viewDidLoad()
self.navigationItem.title = "Tweet"
self.profileImage.setImageWith((self.status?.user.profileImageUrl)!)
self.profileImage.layer.cornerRadius = 9.0
self.profileImage.layer.masksToBounds = true
self.nameLabel.text = self.status?.user.name
self.screennameLabel.text = "@\(self.status!.user.screenname)"
self.statusTextLabel.text = self.status?.text
var formatter = DateFormatter() |
swift |
import UIKit
protocol BoxCoverSelectionViewControllerDelegate: class {
func boxCoverSelectionViewController(_ boxCoverSelectionViewController: BoxCoverSelectionViewController, didSelect url: URL)
}
class BoxCoverSelectionViewController: CardCollectionViewController {
weak var delegate: BoxCoverSelectionViewControllerDelegate?
override func viewDidLoad() {
super.viewDidLoad()
navigationItem.title = NSLocalizedString("Choose Chara", comment: "") |
swift | // Created by ruixingchen on 4/10/19.
// Copyright © 2019 CoolApk. All rights reserved.
//
import Foundation
public extension Swift.Result {
var value:Success? {
return try? self.get() |
swift |
unowned let context: PlayerContext
private let error: PlayerError
// MARK: - Variable
let type: ModernAVPlayer.State = .failed
// MARK: - Init
init(context: PlayerContext, error: PlayerError) {
ModernAVPlayerLogger.instance.log(message: "Init", domain: .lifecycleState)
self.context = context
self.error = error |
swift | if refreshing {
refreshControl?.endRefreshing()
}
SVProgressHUD.dismiss()
return
}
self.posts = []
for item in dict {
let json = JSON(item.value) |
swift |
open class _TimeRow: _DateFieldRow {
required public init(tag: String?) {
super.init(tag: tag)
dateFormatter = DateFormatter() |
swift | }
}
}, fail: { (responseFail) in
if let arrayFail = responseFail as? NSArray , let fail = arrayFail.firstObject as? [String:Any],let errorMessage = fail["ErrorMessage"]{
DispatchQueue.main.async {
ShowToast.show(toatMessage: "\(errorMessage)")
}
}else{
DispatchQueue.main.async {
ShowToast.show(toatMessage:kCommonError)
}
}
}) |
swift | no_escape { _ = self } // OK
do_escape { _ = self } // expected-error {{closure cannot implicitly capture a mutating self parameter}}
}
}
func why_so_sad(line: inout String) {
no_escape { line = "Remember we made an arrangement when you went away" } // OK
do_escape { line = "now you're making me mad" } // expected-error {{escaping closures can only capture inout parameters explicitly by value}}
do_escape { [line] in _ = line } // OK
}
func remember(line: inout String) -> () -> Void {
func despite_our_estrangement() { |
swift | secondImg.setImage(news?.style.images[i], "placeholder")
break
case 2:
thirdImg.setImage(news?.style.images[i], "placeholder")
break
default:
break
}
} |
swift | // iExpense
//
// Created by RAJ RAVAL on 05/02/20.
// Copyright © 2020 Buck. All rights reserved.
//
import UIKit |
swift |
}
override func didReceiveMemoryWarning() { |
swift | private let collectionTableViewDataSource = CollectionTableViewDataSource<CollectionCell>()
private let collectionPreviewTableViewDataSource = CollectionTableViewDataSource<CollectionPreviewCell>()
private var dataSource: UITableViewDataSource? {
didSet {
self.tableView.dataSource = dataSource
self.tableView.reloadData()
}
}
private var storeLayout: StoreLayout = .Basic {
didSet { |
swift |
// TODO: Fix description of check. Failure message is far from perfect.
func test___assertIsDisabled___fails_properly_if_element_is_enabled() {
checkAssertFailsWithDefaultLogs(
failureMessage: """
"проверить, что "isEnabled0" недоступно для нажатия" неуспешно, так как: проверка неуспешна (Имеет проперти isEnabled: equals to false): value is not equal to 'false', actual value: 'true'
""",
body: {
screen.isEnabled0.withoutTimeout.assertIsDisabled() |
swift | class CombineTests: XCTestCase {
let session = URLSession.shared
func testCombineAwait() {
let publisher = session.dataTaskPublisher(for: .testImageURL).map(\.data)
testImageDownload(publisher: publisher)
}
func testCompineSubscriptions() {
let publisher = session.data(for: .testImageURL).map(\.data)
testImageDownload(publisher: publisher)
} |
swift |
public mutating func removeObjectsInArray(_ array: [Element]) {
for object in array {
self.removeObject(object)
}
}
}
extension Array { |
swift | func withAnimation<Result>(_ animation: Animation? = .default, _ body: () throws -> Result) rethrows -> Result {
let callContext = CallContext { action in
SwiftUI.withAnimation(animation) {
action()
}
}
return try CallContext.$current.withValue(callContext) {
try body()
}
} |
swift |
/// HCI Command Status Event
public struct HCICommandStatus: HCIEventParameter {
public static let event = HCIGeneralEvent.commandStatus
public static let length = 4 |
swift |
let indexPath = IndexPath(item: item, section: 0)
let cellWidth = columnWidth
var cellHeight = CGFloat(300)
cellHeight = cellPadding * 2 + cellHeight
let frame = CGRect(x: xOffest[column], y: yOffset[column], width: cellWidth, height: cellHeight)
let insetFrame = frame.insetBy(dx: cellPadding, dy: cellPadding)
let attributes = UICollectionViewLayoutAttributes(forCellWith: indexPath)
attributes.frame = insetFrame |
swift |
static func createNumbersVector(b: inout FlatBufferBuilder, array: [Int]) -> Offset<UOffset> {
b.createVector(array, size: array.count)
}
static func createNumbersVector(b: inout FlatBufferBuilder, array: [Int32]) -> Offset<UOffset> {
b.createVector(array, size: array.count)
}
static func createNumbersVector(b: inout FlatBufferBuilder, array: [Double]) -> Offset<UOffset> {
b.createVector(array, size: array.count) |
swift |
@actorIndependent
var count : Int {
get { storage }
set { storage = newValue }
}
var actorCount : Int {
get { storage }
set { storage = newValue }
}
} |
swift | }
}
class Good: Foo {
let x: Int
// CHECK-LABEL: sil hidden [noinline] @_TFC10super_init4GoodcfT_S0_
// CHECK-NOT: super_method {{%[0-9]+}} : $Good, #Foo.init!initializer.1
// CHECK: [[SUPER_INIT:%.*]] = function_ref @_TFC10super_init3FoocfSiS0_
// CHECK: apply [[SUPER_INIT]]
@inline(never)
override init() {
x = 10
super.init(x)
} |
swift | /// - delay: Double (default delay = 0.5 seconds)
public static func flashScreen(_ delay: Double = 0.5)
{
/// Switch to alternate screen buffer to save current state
/// Reverse Video. For some reason \n is required to activate
Ansi.Set.screenBufferAlternate().stdout()
Ansi.Set.videoReverse().stdout()
Ansi.flush()
Thread.sleep(forTimeInterval: delay)
/// Resume Normal Video. |
swift | * Text("Hello World!")
* }
* .id("xyz")
* }
* }
*
* is NOT the same like |
swift | /// Sets up the underlying service. Eg: FirebaseApp.configure()
func setup()
/// Identifies the user with a unique ID
func identifyUser(with userId: String)
/// Logs an event with it's associated metadata
func log(event: AnalyticsEvent)
} |
swift | // Release any resources associated with this scene that can be re-created the next time the scene connects.
// The scene may re-connect later, as its session was not neccessarily discarded (see `application:didDiscardSceneSessions` instead).
}
func sceneDidBecomeActive(_ scene: UIScene) {
// Called when the scene has moved from an inactive state to an active state.
// Use this method to restart any tasks that were paused (or not yet started) when the scene was inactive.
}
func sceneWillResignActive(_ scene: UIScene) {
// Called when the scene will move from an active state to an inactive state.
// This may occur due to temporary interruptions (ex. an incoming phone call).
} |
swift | final class PrimesTests : XCTestCase {
func testGetPrimeSmall() {
XCTAssertEqual(getPrime(n: 1), 2)
XCTAssertEqual(getPrime(n: 6), 13)
XCTAssertEqual(getPrime(n: 7), 17)
XCTAssertEqual(getPrime(n: 8), 19)
XCTAssertEqual(getPrime(n: 27), 103)
}
func testGetPrimeMedium() {
XCTAssertEqual(getPrime(n: 12323), 131939)
XCTAssertEqual(getPrime(n: 999999), 15485857)
}
}
|
swift | // Created by Foundry on 04/06/2014.
// Copyright (c) 2014 Foundry. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
return true
} |
swift | import SwiftUI
extension Label where Title == Text, Icon == EmptyView {
init(_ titleKey: LocalizedStringKey) {
self.init(title: { Text(titleKey) }, icon: { EmptyView() })
}
} |
swift | logger.log(.verbose, jobId: name, message: "Job has not been scheduled due to \(error.localizedDescription)")
lock.synchronized {
lastError = error
}
// Need to be called manually since the task is actually not in the queue. So cannot call cancel()
handler.onRemove(result: .fail(error))
listener?.onTerminated(job: info, result: .fail(error))
}
public func run() {
if isCancelled && !isFinished {
isFinished = true
}
if isFinished { |
swift | config: config,
resourceFactory: CloudAnalyticsResourceFactory(cloudConfig: config),
client: CloudClient()
)
}
public init(config: Cloud,
resourceFactory: CloudAnalyticsResourceFactorying,
client: CloudClienting) |
swift | }
func getValue<K: RawRepresentable, V>(forKey key: K, default: V) -> V where K.RawValue == String {
return getValue(forKey: key.rawValue, default: `default`)
}
|
swift | //
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
// RUN: %target-run-simple-swift | FileCheck %s
// REQUIRES: executable_test
// Check that the generic parameters are called 'Base' and 'Element'.
protocol TestProtocol1 {}
extension LazyMapGenerator where Base : TestProtocol1, Element : TestProtocol1 { |
swift | // DO NOT EDIT
// swiftlint:disable line_length identifier_name
import UIKit
@available(iOS 2.0, *)
extension Configurable where Self: UISlider {
@discardableResult public func apply(_ configuration: ConfigurationSet<UISlider>) -> Self {
_ = configuration.apply(on: self as UISlider)
return self |
swift | .onDelete { viewStore.send(.remove($0)) }
}
}
.navigationBarTitle(viewStore.state.isEmpty ? "Untitled" : viewStore.state)
.navigationBarItems(
trailing: Button("Add row") { viewStore.send(.append) }
)
}
}
}
extension NestedState {
static let mock = NestedState(
children: [ |
swift | // MARK: Table View
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return tweets?.count ?? 0
}
|
swift | func check(button: XCUIElement) {
XCTAssert(button.frame.size.height >= 44)
XCTAssert(button.frame.size.width >= 44)
XCTAssertTrue(button.label.count <= 40)
XCTAssert(button.label.first!.isUppercase)
}
// Listing 11-2
func test_imageName() {
// Navigate to the screen you want to check
XCUIApplication().tabBars.buttons["Tests"].tap()
|
swift | required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func addAnimate() {
var beginTime = AVCoreAnimationBeginTimeAtZero + anim1Duration |
swift | XCTAssertEqual(decoded.date, secondsSince1970)
expect.fulfill()
}
let post = PostWithDate(name: "Test", date: Date(timeIntervalSince1970: secondsSince1970))
let api = ConvAPI(requester: mockRequester)
api.encoder.dateEncodingStrategy = .secondsSince1970
api.request(method: .POST, baseURL: ConvAPITests.url, body: post, error: APIError.self).cauterize()
wait(for: [expect], timeout: 5)
}
func testCallDecorator() { |
swift | }
}
public var minute: Int {
return components(.minute) {
return $0.minute ?? 0
}
}
public var hour: Int {
return components(.hour) {
return $0.hour ?? 0
}
} |
swift | var reloadDataCount = 0
beforeEach {
let (signal, observer) = Signal<(), Never>.pipe()
(bindingSignal, bindingObserver) = (signal, observer)
reloadDataCount = 0 |
swift | func deleteAll<T: Storable>(_ model: T.Type) throws {
guard let storable = model as? Object.Type else {
throw RealmDatabaseError.objectCouldNotBeParsed
}
try writeSafely { [weak self] in
guard let self = self else { return }
|
swift | }
@objc public func removeAddress(_ address: FBAddressBean ,ip: IndexPath) {
FBHud.show(withStatus: "删除地址中...")
FBAddressViewModel
.removeAddress(address.encoded)
.drive(onNext: { [weak self] (result) in
guard let `self` = self else { return }
switch result {
case .ok: |
swift | // MARK: - Application Status
var isApplicationActive = true
private func registerNotifications() {
NotificationCenter.default.addObserver(self, selector: #selector(_applicationDidActive(_:)), name: UIApplication.didBecomeActiveNotification, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(_applicationWillInactive(_:)), name: UIApplication.willResignActiveNotification, object: nil)
}
@objc private func _applicationDidActive(_ notification: Notification) {
Logger.info("OneKey _applicationDidActive at \(Date().timeIntervalSince1970)")
isApplicationActive = true
lockQueue.async { |
swift |
static var twitter: DateFormatter = {
let formatter = DateFormatter()
formatter.locale = Locale(identifier: "en_US_POSIX")
formatter.dateFormat = "EEE MMM dd HH:mm:ss Z yyyy"
return formatter |
swift | }
}
/// An option item to set a numeric value.
@IBDesignable open class NumericOptionItem: OptionItem {
// MARK: - Properties
/// The value set for the option.
public var value: NSNumber? {
didSet {
// Any value? |
swift | return UnitDatabaseQueries()
.getUnits(armyId: nil, unitType: nil, conn: req)
.flatMap(to: View.self, { units in
let context = UnitsContext(title: "Units", units: units)
return try req.view().render("units", context)
})
}
func unitHandler(_ req: Request) throws -> Future<View> {
let armyId = try req.parameters.next(Int.self)
let unitId = try req.parameters.next(Int.self)
let armyFuture = try ArmyController().getArmy(byID: armyId, conn: req) |
swift | public enum HTTPCode: StatusCode, JSONSerializable {
//2xx Success codes
case ok = 200
case created = 201
case accepted = 202
case nonAuthoritativeInformation = 203
case noContent = 204
case resetContent = 205
case partialContent = 206 |
swift |
func sceneDidDisconnect(_ scene: UIScene) {
// Called as the scene is being released by the system.
// This occurs shortly after the scene enters the background, or when its session is discarded.
// Release any resources associated with this scene that can be re-created the next time the scene connects. |
swift | // Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
protocol f {
k g d {
k d
k k
}
j j<l : d> : d {
k , d> |
swift |
@IBInspectable var name: String? {
get { return nameLabel.text }
set { nameLabel.text = newValue }
}
@IBInspectable var profession: String? {
get { return professionLabel.text }
set { professionLabel.text = newValue }
}
@IBInspectable var image: UIImage? { |
swift | // Copyright © 2020 yousefahmza. All rights reserved.
//
import UIKit
class FlickerCollectionViewCell: UICollectionViewCell {
lazy var flickImageView: UIImageView = {
let imageView = UIImageView()
imageView.contentMode = .scaleAspectFill |
swift | let uploadTask1 = session0.uploadTask(with: request, from: Data(), completionHandler: {
(data, response, error) -> Void in
//print("upload - \(response)")
}
)
uploadTask1.resume()
/// upload file
if let filePath = Bundle.main.url(forResource: "subway-lister", withExtension: "json") {
print("upload filePath: \(filePath)")
let uploadTask2 = session0.uploadTask(with: request, fromFile: filePath, completionHandler: {
(data, repsonse, error) -> Void in |
swift | import SwiftUI
///Contains State of the sheet & raw value with offset value
public enum BottomSheetState: CGFloat {
case expanded = 100
case collapsed = 500
case dismissed = 1000
}
|
swift |
class LinkedListReferenceType {
var value: String
var next: LinkedListReferenceType?
init(value: String) {
self.value = value
}
}
|
swift |
public final class SnapshotsDifferenceAttachmentGeneratorImpl: SnapshotsDifferenceAttachmentGenerator {
private let differenceImageGenerator: DifferenceImageGenerator
public init(differenceImageGenerator: DifferenceImageGenerator) {
self.differenceImageGenerator = differenceImageGenerator
}
public func attachments(snapshotsDifferenceDescription: SnapshotsDifferenceDescription) -> [Attachment] {
var attachments = [ |
swift | }
}
private extension NetworkReachabilityManager.ConnectionType {
var name: String {
switch self {
case .ethernetOrWiFi:
return "ethernetOrWiFi" |
swift | var result = BorderStyle()
if let color = layer.borderColor, color != UIColor.clear.cgColor {
result.colors = [UIColor(cgColor: color)]
}
result.width = layer.borderWidth
return result
}
} |
swift |
XCTAssertEqual(e.description, expected)
}
func testImport() {
let imp = TSImportDecl(names: ["A", "B", "C"], from: "..")
let expected = """
import {
A,
B,
C
} from "..";
""" |
swift | XCTAssertEqual(unit, EnergyFormatter.Unit.calorie)
XCTAssertEqual(formatter.unitString(fromJoules: 4185, usedUnit: &unit), "kcal")
XCTAssertEqual(unit, EnergyFormatter.Unit.kilocalorie)
XCTAssertEqual(formatter.unitString(fromJoules: 100000, usedUnit: &unit), "kcal")
XCTAssertEqual(unit, EnergyFormatter.Unit.kilocalorie)
formatter.numberFormatter.locale = Locale(identifier: "de_DE")
XCTAssertEqual(formatter.unitString(fromJoules: -100000, usedUnit: &unit), "kJ")
XCTAssertEqual(unit, EnergyFormatter.Unit.kilojoule) |
swift | }
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) { |
swift | var genre: Int?
var region: String?
if selectedDate > 0 {
startDate = datesInt[selectedDate]
endDtate = startDate! + 10
}
if selectedGenre > 0 {
genre = genres![selectedGenre].id
}
if selectedCountry > 0 {
region = NSLocale.isoCountryCodes[selectedCountry - 1] |
swift | //
// Created by mani on 2020-10-06.
// Copyright © 2020 mani. All rights reserved.
//
import XCTest
@testable import CurrencyConverter |
swift | /**
Deletes database file, then copies a fresh SQLite database file to replace it.
Useful for testing but NOT RECOMMENDED for production use.
*/
public func newDatabase() {
db.deleteDatabase()
let resetDB = db.didResetDatabase() |
swift | // TODO: Use nib for cell once we drop iOS 8 and can use layouts
if #available(iOS 9.0, tvOS 9.0, *) {
#if os(iOS)
internalCollectionView.register(UINib(nibName: "PVGameLibraryCollectionViewCell", bundle: nil), forCellWithReuseIdentifier: PVGameLibraryCollectionViewCellIdentifier)
#else
internalCollectionView.register(UINib(nibName: "PVGameLibraryCollectionViewCell~tvOS", bundle: nil), forCellWithReuseIdentifier: PVGameLibraryCollectionViewCellIdentifier) |
swift | var stmt = OpaquePointer(bitPattern: 0) {
didSet {
var tables: Set<String> = [ ]
for column in 0..<sqlite3_column_count(stmt) {
keys.append(String(cString: sqlite3_column_name(stmt, column)))
tables.insert(String(cString: sqlite3_column_table_name(stmt, column)))
}
self.updateHook = { [weak self, tables] (type: Int32, table: String, rowid: Int64) in
if tables.contains(table) {
self?.reloadData()
}
}
} |
swift |
func testPerformanceExample() {
// This is an example of a performance test case.
self.measureBlock {
// Put the code you want to measure the time of here.
}
}
}
|
swift |
public enum HTTPTask {
case request
case requestParameters(bodyParameters: Parameters?,
bodyEncoding: ParameterEncoding,
urlParameters: Parameters?) |
swift |
let multilineTextFieldControllerUnderlineTrailingView =
MDCTextInputControllerUnderline(textInput: multilineTextFieldTrailingView)
multilineTextFieldControllerUnderlineTrailingView.isFloatingEnabled = false
multilineTextFieldControllerUnderlineTrailingView.placeholderText = "This has a trailing view"
let multilineTextFieldCustomFont = MDCMultilineTextField()
multilineTextFieldCustomFont.translatesAutoresizingMaskIntoConstraints = false
scrollView.addSubview(multilineTextFieldCustomFont)
let multilineTextFieldControllerUnderlineCustomFont =
MDCTextInputControllerUnderline(textInput: multilineTextFieldCustomFont)
multilineTextFieldControllerUnderlineCustomFont.placeholderText = "This has a custom font"
|
swift | @objc dynamic var shouldPlannerTutorial: Bool = true
@objc dynamic var shouldRoutineTutorial: Bool = true
@objc dynamic var shouldStopwatchTutorial: Bool = true
@objc dynamic var shouldChartsTutorial: Bool = true
@objc dynamic var shouldTimelineTutorial: Bool = true
@objc dynamic var shouldCalendarTutorial: Bool = true
@objc dynamic var shouldCustomColorTutorial: Bool = true
} |
swift | let dewPoint: Double? // optional. The dew point in degrees Fahrenheit.
let humidity: Double? // optional. The relative humidity, between 0 and 1, inclusive.
let moonPhase: Double? // optional, only on daily. The fractional part of the lunation number during the given day: a value of 0 corresponds to a new moon, 0.25 to a first quarter moon, 0.5 to a full moon, and 0.75 to a last quarter moon. (The ranges in between these represent waxing crescent, waxing gibbous, waning gibbous, and waning crescent moons, respectively.)
let nearestStormBearing: Double? // optional, only on currently. The approximate direction of the nearest storm in degrees, with true north at 0° and progressing clockwise. (If nearestStormDistance is zero, then this value will not be defined.)
let nearestStormDistance: Double? // optional, only on currently. The approximate distance to the nearest storm in miles. (A storm distance of 0 doesn’t necessarily refer to a storm at the requested location, but rather a storm in the vicinity of that location.)
let ozone: Double? // optional. The columnar density of total atmospheric ozone at the given time in Dobson units.
let precipAccumulation: Double? // optional, only on hourly and daily. The amount of snowfall accumulation expected to occur, in inches. (If no snowfall is expected, this property will not be defined.) |