hexsha
stringlengths 40
40
| size
int64 3
1.03M
| content
stringlengths 3
1.03M
| avg_line_length
float64 1.33
100
| max_line_length
int64 2
1k
| alphanum_fraction
float64 0.25
0.99
|
---|---|---|---|---|---|
283220f3651489d4dec5691f73eb96c76f42ea40 | 1,147 | //
// Constants.swift
// GitHubSearch
//
// Created by Genek on 5/3/18.
// Copyright © 2018 Yevhen Tsyhanenko. All rights reserved.
//
import Foundation
struct API {
struct URL {
static let host = "https://api.github.com/"
static let searchRepositoriesPath = "search/repositories"
}
struct Keys {
static let searchQuery = "q"
static let order = "order"
static let sort = "sort"
static let stars = "stars"
static let page = "page"
static let perPage = "per_page"
static let authorization = "Authorization"
static let token = "token"
static let items = "items"
static let url = "html_url"
static let starsCount = "stargazers_count"
static let name = "name"
}
// Token is encrypted, decrypt for use
static let authorizationToken = "4d3793h5i7i5dg<568399ff796:d7f85<7;d444i"
}
struct Constants {
static let search = "Search"
static let repositoriesPerPage = 15
static let repositoriesPageCount = 2
static let searchResultMaxLength = 30
static let starsCountKey = "starsCount"
}
| 26.674419 | 78 | 0.636443 |
e95efb24157c95449e38c0bea8bfe1add2c56608 | 850 | // RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk) -parse %s -verify
// REQUIRES: objc_interop
import Foundation
func testDictionary() {
// -[NSDictionary init] returns non-nil.
var dictNonOpt = NSDictionary()
_ = dictNonOpt! // expected-error {{cannot force unwrap value of non-optional type 'NSDictionary'}}
}
func testString() throws {
// Optional
let stringOpt = NSString(path: "blah", encoding: 0)
_ = stringOpt as NSString // expected-error{{value of optional type 'NSString?' not unwrapped; did you mean to use '!' or '?'?}}
// Implicitly unwrapped optional
let stringIUO = NSString(path: "blah")
if stringIUO == nil { }
_ = stringIUO as NSString?
let _: NSString = NSString(path: "blah")
}
func testHive() {
let hiveIUO = Hive()
if hiveIUO == nil { }
_ = hiveIUO as Hive?
let _: Hive = Hive()
}
| 27.419355 | 130 | 0.676471 |
d598935827159aa32dfd8cb244d521f162a6e2c1 | 5,275 | // RestoreWalletFromSeedsProgressModel.swift
/*
Package MobileWallet
Created by Adrian Truszczynski on 27/07/2021
Using Swift 5.0
Running on macOS 12.0
Copyright 2019 The Tari Project
Redistribution and use in source and binary forms, with or
without modification, are permitted provided that the
following conditions are met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
3. Neither the name of the copyright holder nor the names of
its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
import Combine
import UIKit
final class RestoreWalletFromSeedsProgressModel {
final class ViewModel {
@Published var status: String? = localized("restore_from_seed_words.progress_overlay.status.connecting")
@Published var progress: String?
@Published var error: SimpleErrorModel?
@Published var isWalletRestored: Bool = false
}
// MARK: - Properties
let viewModel = ViewModel()
private var cancelables: Set<AnyCancellable> = []
// MARK: - Initializers
init() {
registerOnRestoreProgressCallbacks()
}
// MARK: - Setups
private func registerOnRestoreProgressCallbacks() {
NotificationCenter.default.publisher(for: UIApplication.didBecomeActiveNotification)
.sink { [weak self] _ in
self?.resumeRestoringWallet()
}
.store(in: &cancelables)
TariEventBus
.events(forType: .restoreWalletStatusUpdate)
.compactMap { $0.object as? RestoreWalletStatus }
.sink { [weak self] in self?.handle(restoreStatus: $0) }
.store(in: &cancelables)
}
// MARK: - Actions
func startRestoringWallet() {
do {
let result = try TariLib.shared.tariWallet?.startRecovery()
if result == false {
handleStartRecoveryFailure()
}
} catch {
handleStartRecoveryFailure()
}
}
private func resumeRestoringWallet() {
WalletConnectivityManager.startWallet { [weak self] result in
switch result {
case .success:
self?.startRestoringWallet()
case .failure:
self?.handleStartRecoveryFailure()
}
}
}
// MARK: - Handlers
private func handle(restoreStatus: RestoreWalletStatus) {
switch restoreStatus {
case .connectingToBaseNode:
return
case .connectedToBaseNode:
viewModel.status = localized("restore_from_seed_words.progress_overlay.status.connected")
viewModel.progress = nil
viewModel.error = nil
case let .connectionFailed(attempt, maxAttempts), let .scanningRoundFailed(attempt, maxAttempts):
viewModel.status = localized("restore_from_seed_words.progress_overlay.status.connecting")
viewModel.progress = localized("restore_from_seed_words.progress_overlay.progress.connection_failed", arguments: attempt + 1, maxAttempts + 1)
viewModel.error = nil
case let .progress(restoredUTXOs, totalNumberOfUTXOs):
let value = Double(restoredUTXOs) / Double(totalNumberOfUTXOs) * 100.0
viewModel.status = localized("restore_from_seed_words.progress_overlay.status.progress")
viewModel.progress = String(format: "%.1f%%", value)
viewModel.error = nil
case .completed:
viewModel.isWalletRestored = true
case .recoveryFailed, .unknown:
viewModel.error = SimpleErrorModel(
title: localized("restore_from_seed_words.progress_overlay.error.title"),
description: localized("restore_from_seed_words.progress_overlay.error.description.connection_failed")
)
}
}
private func handleStartRecoveryFailure() {
viewModel.error = SimpleErrorModel(
title: localized("restore_from_seed_words.progress_overlay.error.title"),
description: localized("restore_from_seed_words.progress_overlay.error.description.unknown_error")
)
}
}
| 37.147887 | 154 | 0.687583 |
08900058f6a60e12f0eb767e98b24b845e3d07ae | 1,515 | import AlamofireImage
import Alamofire
extension AlamofireImage.ImageDownloader: CachingImageDownloader {
public func downloadImageAtUrl(
_ url: URL,
progressHandler: ((_ receivedSize: Int64, _ expectedSize: Int64) -> ())?,
completion: @escaping (_ image: CGImage?, _ error: Error?) -> ())
-> CancellableImageDownload
{
let request = URLRequest(url: url)
let progress: (Progress) -> () = { progress in
progressHandler?(progress.completedUnitCount, progress.totalUnitCount)
}
let downloadCompletion: (DataResponse<UIImage, AFIError>) -> () = { response in
let image = response.value
completion(image?.cgImage, response.error)
}
let requestReceipt = download(
request,
progress: progress,
completion: downloadCompletion)
return AlamofireCancellableImageDownloadAdapter(receipt: requestReceipt)
}
public func cachedImageForUrl(_ url: URL) -> CGImage? {
let request = URLRequest(url: url)
if let image = imageCache?.image(for: request, withIdentifier: nil) {
return image.cgImage
} else {
return nil
}
}
}
final class AlamofireCancellableImageDownloadAdapter: CancellableImageDownload {
let receipt: RequestReceipt?
init(receipt: RequestReceipt?) {
self.receipt = receipt
}
func cancel() {
receipt?.request.cancel()
}
}
| 30.918367 | 87 | 0.622442 |
90a189246c4c75360fd6fc5a6591e873fd1fd332 | 3,050 | //
// NSConstraintLayoutSet.swift
// InputBarAccessoryView
//
// Copyright © 2017-2019 Nathan Tannar.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
// Created by Nathan Tannar on 8/25/17.
//
import Foundation
import UIKit
class NSLayoutConstraintSet {
var top: NSLayoutConstraint?
var bottom: NSLayoutConstraint?
var left: NSLayoutConstraint?
var right: NSLayoutConstraint?
var centerX: NSLayoutConstraint?
var centerY: NSLayoutConstraint?
var width: NSLayoutConstraint?
var height: NSLayoutConstraint?
public init(top: NSLayoutConstraint? = nil,
bottom: NSLayoutConstraint? = nil,
left: NSLayoutConstraint? = nil,
right: NSLayoutConstraint? = nil,
centerX: NSLayoutConstraint? = nil,
centerY: NSLayoutConstraint? = nil,
width: NSLayoutConstraint? = nil,
height: NSLayoutConstraint? = nil) {
self.top = top
self.bottom = bottom
self.left = left
self.right = right
self.centerX = centerX
self.centerY = centerY
self.width = width
self.height = height
}
/// All of the currently configured constraints
private var availableConstraints: [NSLayoutConstraint] {
#if swift(>=4.1)
return [top, bottom, left, right, centerX, centerY, width, height].compactMap {$0}
#else
return [top, bottom, left, right, centerX, centerY, width, height].flatMap {$0}
#endif
}
/// Activates all of the non-nil constraints
///
/// - Returns: Self
@discardableResult
func activate() -> Self {
NSLayoutConstraint.activate(availableConstraints)
return self
}
/// Deactivates all of the non-nil constraints
///
/// - Returns: Self
@discardableResult
func deactivate() -> Self {
NSLayoutConstraint.deactivate(availableConstraints)
return self
}
}
| 35.057471 | 94 | 0.664918 |
e68215fd814764579295de8b19beeb51da0a21c5 | 881 | //
// PiecesViewController.swift
// Prhymer
//
// Created by Thomas Lisankie on 6/13/16.
// Copyright © 2016 Shaken Earth. All rights reserved.
//
import UIKit
class PiecesViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| 24.472222 | 106 | 0.677639 |
727f6bdeb118348b04a54ec54a8c35da5b1c554d | 2,190 | //
// AppDelegate.swift
// ARKit_VirtualObjects
//
// Created by Salman Qureshi on 11/26/17.
// Copyright © 2017 Salman Qureshi. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
| 46.595745 | 285 | 0.757078 |
7aefcf48a89c1d31410a18affcb4c42d700bf0db | 6,940 | // Copyright SIX DAY LLC. All rights reserved.
import XCTest
@testable import AlphaWallet
import TrustKeystore
class FakeUrlSchemeCoordinator: UrlSchemeCoordinatorType {
static func make() -> FakeUrlSchemeCoordinator {
return .init()
}
func handleOpen(url: URL) -> Bool {
return false
}
func processPendingURL(in inCoordinator: UrlSchemeResolver) {
//no op
}
}
class InCoordinatorTests: XCTestCase {
func testShowTabBar() {
let config: Config = .make()
let wallet: Wallet = .make()
let coordinator = InCoordinator(
navigationController: FakeNavigationController(),
wallet: .make(),
keystore: FakeKeystore(wallets: [wallet]),
assetDefinitionStore: AssetDefinitionStore(),
config: config,
analyticsCoordinator: FakeAnalyticsService(),
urlSchemeCoordinator: FakeUrlSchemeCoordinator.make()
)
coordinator.start()
let tabbarController = coordinator.navigationController.viewControllers[0] as? UITabBarController
XCTAssertNotNil(tabbarController)
XCTAssert(tabbarController?.viewControllers!.count == 4)
XCTAssert((tabbarController?.viewControllers?[0] as? UINavigationController)?.viewControllers[0] is TokensViewController)
XCTAssert((tabbarController?.viewControllers?[1] as? UINavigationController)?.viewControllers[0] is ActivitiesViewController)
XCTAssert((tabbarController?.viewControllers?[2] as? UINavigationController)?.viewControllers[0] is DappsHomeViewController)
XCTAssert((tabbarController?.viewControllers?[3] as? UINavigationController)?.viewControllers[0] is SettingsViewController)
}
func testChangeRecentlyUsedAccount() {
let account1: Wallet = .make(type: .watch(AlphaWallet.Address(string: "0x1000000000000000000000000000000000000000")!))
let account2: Wallet = .make(type: .watch(AlphaWallet.Address(string: "0x2000000000000000000000000000000000000000")!))
let keystore = FakeKeystore(
wallets: [
account1,
account2
]
)
let coordinator = InCoordinator(
navigationController: FakeNavigationController(),
wallet: .make(),
keystore: keystore,
assetDefinitionStore: AssetDefinitionStore(),
config: .make(),
analyticsCoordinator: FakeAnalyticsService(),
urlSchemeCoordinator: FakeUrlSchemeCoordinator.make()
)
coordinator.showTabBar(for: account1)
XCTAssertEqual(coordinator.keystore.currentWallet, account1)
coordinator.showTabBar(for: account2)
XCTAssertEqual(coordinator.keystore.currentWallet, account2)
}
func testShowSendFlow() {
let wallet: Wallet = .make()
let coordinator = InCoordinator(
navigationController: FakeNavigationController(),
wallet: wallet,
keystore: FakeKeystore(wallets: [wallet]),
assetDefinitionStore: AssetDefinitionStore(),
config: .make(),
analyticsCoordinator: FakeAnalyticsService(),
urlSchemeCoordinator: FakeUrlSchemeCoordinator.make()
)
coordinator.showTabBar(for: .make())
coordinator.showPaymentFlow(for: .send(type: .nativeCryptocurrency(TokenObject(), destination: .none, amount: nil)), server: .main, navigationController: coordinator.navigationController)
XCTAssertTrue(coordinator.coordinators.last is PaymentCoordinator)
XCTAssertTrue(coordinator.navigationController.viewControllers.last is SendViewController)
}
func testShowRequstFlow() {
let wallet: Wallet = .make()
let coordinator = InCoordinator(
navigationController: FakeNavigationController(),
wallet: wallet,
keystore: FakeKeystore(wallets: [wallet]),
assetDefinitionStore: AssetDefinitionStore(),
config: .make(),
analyticsCoordinator: FakeAnalyticsService(),
urlSchemeCoordinator: FakeUrlSchemeCoordinator.make()
)
coordinator.showTabBar(for: .make())
coordinator.showPaymentFlow(for: .request, server: .main, navigationController: coordinator.navigationController)
XCTAssertTrue(coordinator.coordinators.last is PaymentCoordinator)
XCTAssertTrue(coordinator.navigationController.viewControllers.last is RequestViewController)
}
func testShowTabDefault() {
let coordinator = InCoordinator(
navigationController: FakeNavigationController(),
wallet: .make(),
keystore: FakeKeystore(),
assetDefinitionStore: AssetDefinitionStore(),
config: .make(),
analyticsCoordinator: FakeAnalyticsService(),
urlSchemeCoordinator: FakeUrlSchemeCoordinator.make()
)
coordinator.showTabBar(for: .make())
let viewController = (coordinator.tabBarController?.selectedViewController as? UINavigationController)?.viewControllers[0]
XCTAssert(viewController is TokensViewController)
}
//Commented out because the tokens tab has been moved to be under the More tab and will be moved
// func testShowTabTokens() {
// let coordinator = InCoordinator(
// navigationController: FakeNavigationController(),
// wallet: .make(),
// keystore: FakeEtherKeystore(),
// config: .make()
// )
// coordinator.showTabBar(for: .make())
// coordinator.showTab(.tokens)
// let viewController = (coordinator.tabBarController?.selectedViewController as? UINavigationController)?.viewControllers[0]
// XCTAssert(viewController is TokensViewController)
// }
func testShowTabAlphwaWalletWallet() {
let keystore = FakeEtherKeystore()
switch keystore.createAccount() {
case .success(let account):
let wallet = Wallet(type: .real(account))
keystore.recentlyUsedWallet = wallet
let coordinator = InCoordinator(
navigationController: FakeNavigationController(),
wallet: wallet,
keystore: keystore,
assetDefinitionStore: AssetDefinitionStore(),
config: .make(),
analyticsCoordinator: FakeAnalyticsService(),
urlSchemeCoordinator: FakeUrlSchemeCoordinator.make()
)
coordinator.showTabBar(for: wallet)
coordinator.showTab(.wallet)
let viewController = (coordinator.tabBarController?.selectedViewController as? UINavigationController)?.viewControllers[0]
XCTAssert(viewController is TokensViewController)
case .failure:
XCTFail()
}
}
}
| 38.77095 | 195 | 0.659222 |
3813969431a150512bf9b32d7856c7b388ec1c26 | 1,247 | //
// DismissModalAnimator.swift
// breadwallet
//
// Created by Adrian Corscadden on 2016-11-25.
// Copyright © 2016 breadwallet LLC. All rights reserved.
//
import UIKit
//TODO - figure out who should own this
let blurView = UIVisualEffectView()
class DismissModalAnimator : NSObject, UIViewControllerAnimatedTransitioning {
func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval {
return 0.4
}
func animateTransition(using transitionContext: UIViewControllerContextTransitioning) {
guard transitionContext.isAnimated else { return }
let duration = transitionDuration(using: transitionContext)
guard let fromView = transitionContext.view(forKey: .from) else { assert(false, "Missing from view"); return }
UIView.animate(withDuration: duration, animations: {
blurView.alpha = 0.0 //Preferrably, this would animatate .effect, but it's not playing nicely with UIPercentDrivenInteractiveTransition
fromView.frame = fromView.frame.offsetBy(dx: 0, dy: fromView.frame.height)
}, completion: { _ in
transitionContext.completeTransition(!transitionContext.transitionWasCancelled)
})
}
}
| 37.787879 | 147 | 0.728949 |
e9d43ad6091e701275b97d5fbb0f270b8d1c0631 | 667 | //
// DistanceRepresentable.swift
// ARQuest
//
// Created by Anton Poltoratskyi on 30.04.2018.
// Copyright © 2018 Anton Poltoratskyi. All rights reserved.
//
import CoreLocation
import SceneKit
protocol DistanceRepresentable {
associatedtype Target
func distance(to target: Target) -> Distance
}
extension CLLocation: DistanceRepresentable {
func distance(to target: CLLocation) -> Distance {
return self.distance(from: target)
}
}
extension CameraTransform: DistanceRepresentable {
func distance(to target: CameraTransform) -> Distance {
return Distance(translationVector.distance(to: target.translationVector))
}
}
| 23.821429 | 81 | 0.733133 |
f9c222c06058b2d7b9dd4114753df4f5afa4fc59 | 222 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
struct d
{
var b {
if true {
case
( [ {
class
case ,
| 17.076923 | 87 | 0.725225 |
8f28b250757f18b0fefe19321316a92857999dfa | 2,485 | //
// Actors2D.swift
//
// Created by Zack Brown on 28/03/2021.
//
import Meadow
import SpriteKit
public class Actors2D: SKNode, Codable, Responder2D, Soilable {
private enum CodingKeys: String, CodingKey {
case npcs = "n"
}
public var ancestor: SoilableParent? { parent as? SoilableParent }
public var isDirty: Bool = false
public var npcs: [Actor2D] = []
override init() {
super.init()
becomeDirty()
}
required public init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
npcs = try container.decode([Actor2D].self, forKey: .npcs)
super.init()
for actor in npcs {
addChild(actor)
}
becomeDirty()
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
public func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(npcs, forKey: .npcs)
}
@discardableResult public func clean() -> Bool {
guard isDirty else { return false }
for actor in npcs {
actor.clean()
}
isDirty = false
return true
}
public typealias ActorConfiguration = ((Actor2D) -> Void)
public func add(actor coordinate: Coordinate, configure: ActorConfiguration? = nil) -> Actor2D? {
guard let map = map,
map.validate(coordinate: coordinate, grid: .actors) else { return nil }
let actor = Actor2D(coordinate: coordinate)
npcs.append(actor)
addChild(actor)
configure?(actor)
becomeDirty()
return actor
}
}
extension Actors2D {
public func find(actor coordinate: Coordinate) -> Actor2D? {
return npcs.first { $0.coordinate.xz == coordinate.xz }
}
public func remove(actor coordinate: Coordinate) {
guard let actor = find(actor: coordinate),
let index = npcs.firstIndex(of: actor) else { return }
npcs.remove(at: index)
actor.removeFromParent()
becomeDirty()
}
}
| 22.1875 | 101 | 0.531187 |
bb3fd55cc618eff0f707e0bd49b18118d3da734f | 1,085 | struct BasicInfomation {
let name: String
var age: Int
}
var yagomInfo: BasicInfomation = BasicInfomation(name: "yagom", age: 99)
yagomInfo.age = 100
var friendInfo: BasicInfomation = yagomInfo
print("yagom's age: \(yagomInfo.age)")
print("friend's age: \(friendInfo.age)")
friendInfo.age = 999
print("yagom's age: \(yagomInfo.age)")
print("friend's age: \(friendInfo.age)")
class Person {
var height: Float = 0.0
var weight: Float = 0.0
}
var yagom: Person = Person()
var friend: Person = yagom
print("yagom's height: \(yagom.height)")
print("friend's height: \(friend.height)")
friend.height = 185.5
print("yagom's height: \(yagom.height)")
// 185.5 - friend가 yagom을 참조하기 때문에 값이 변동된다.
func changeBasicInfo(_ info: BasicInfomation) {
var copiedInfo: BasicInfomation = info
copiedInfo.age = 1
}
func changePersonInfo(_ info: Person) {
info.height = 155.3
}
changeBasicInfo(yagomInfo)
// 전달되는 인자로 값이 복사되어 전달되어서 최종적으로 yagomInfo에 영향을 주지 않는다.
print("yagom's age: \(yagomInfo.age)")
changePersonInfo(yagom)
print("yagom's height: \(yagom.height)")
| 21.7 | 72 | 0.700461 |
62efe60b70e2f57690c9b19cd2b32a8f9f34a7dc | 454 | //
// Contact.swift
// Chat App for iOS 10
//
// Created by apple on 6/7/18.
// Copyright © 2018 Frank Nerdy. All rights reserved.
//
import Foundation
class Contact {
private var _name = "";
private var _id = "";
init(id: String, name: String) {
_id = id;
_name = name;
}
var name: String {
get {
return _name;
}
}
var id: String {
return _id;
}
}
| 15.133333 | 54 | 0.497797 |
7a7e48257e87e0262dec24d8a4f564eb4401ca3c | 858 | //
// UserRepositoryImpl.swift
// CodeBaseProject
//
// Created by HaiKaito on 10/04/2022.
//
import Foundation
class UserRepositoryImpl: UserRepository {
@Inject private var network: UserNetwork
@Inject private var local: UserLocal // TODO: Hanlde to save data
func userInfo(inputUrl: UrlInputUserInfo) async -> FinalResult<UserEntity> {
return await network.userInfo(inputUrl: inputUrl)
}
func userEmail(inputUrl: UrlInputUserInfo) async -> FinalResult<UserEmailEntity> {
return await network.userEmail(inputUrl: inputUrl)
}
func register(inputBody: BodyInputUserInfo) async -> FinalResult<Bool> {
return await network.register(inputBody: inputBody)
}
func update(inputUrl: UrlInputUserInfo, inputBody: BodyInputUserInfo) async -> FinalResult<Bool> {
return await network.update(inputUrl: inputUrl, inputBody: inputBody)
}
}
| 28.6 | 99 | 0.765734 |
d66f2d8c14af490c392a1b5c6b86899e87ec97fb | 4,024 | //
// TableViewController.swift
// NumberGuesser_2
//
// Created by Moritz Lechthaler on 16.12.21.
//
import UIKit
class TableViewController: UITableViewController {
let queue = DispatchQueue(label: "download")
let path = "https://jsonplaceholder.typicode.com/todos"
var model = ToDoModel()
override func viewDidLoad() {
super.viewDidLoad()
if let url = URL(string: path){
queue.async {
let todo = self.download(url: url)
DispatchQueue.main.async {
self.model.todos = todo
self.tableView.reloadData()
}
}
}
}
// MARK: - Table view data source
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return model.todos.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "reuseIdentifier", for: indexPath)
UITableViewCell{
let cell = tableView.dequeueReusableCell(withIdentifier: "todo", for: indexPath)
let todo = model.[indexPath.row]
cell.textLabel?.text = todo.titel
cell.detailTextLabel
}
return cell
}
/*
// Override to support conditional editing of the table view.
override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
// Return false if you do not want the specified item to be editable.
return true
}
*/
/*
// Override to support editing the table view.
override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == .delete {
// Delete the row from the data source
tableView.deleteRows(at: [indexPath], with: .fade)
} else if editingStyle == .insert {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
}
}
*/
/*
// Override to support rearranging the table view.
override func tableView(_ tableView: UITableView, moveRowAt fromIndexPath: IndexPath, to: IndexPath) {
}
*/
/*
// Override to support conditional rearranging of the table view.
override func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool {
// Return false if you do not want the item to be re-orderable.
return true
}
*/
/*
// 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?) {
// Get the new view controller using segue.destination.
// Pass the selected object to the new view controller.
}
*/
func download(url: URL) -> [ToDo] {
print("downloading \(url)")
var todos = [ToDo]()
if let data = try? Data(contentsOf: url){
print("data is \(data)")
let obj = try? JSONSerialization.jsonObject(with: data, options: [])
if let array = obj as? [[String: Any]] {
for el in array {
let todo = ToDo()
if let id = el ["id"] as? Int, let titel = el ["titel"] as? String{
todo.id = id
todo.titel = titel
todos.append(todo)
print("id: \(id), titel: \(titel)")
}
}
// print("data is \(array)")
}
// print("data is \(obj)")
}else{
print("ka download")
}
return todos
}
}
| 32.451613 | 137 | 0.574801 |
6a0c3f87be8dccf00191e47fd65196022f78bde3 | 3,593 | //
// MetalViewController.swift
// VCamera
//
// Created by VassilyChi on 2019/12/25.
// Copyright © 2019 VassilyChi. All rights reserved.
//
import UIKit
import MetalKit
import AVFoundation
import Galilei
import Combine
import CoreImage
import MetalPerformanceShaders
import SnapKit
import Vincent
class MetalViewController: UIViewController {
private var metalView: MTKView
private var blurView = UIVisualEffectView(effect: UIBlurEffect(style: .light))
private var viewH: Constraint!
private var viewW: Constraint!
private var viewTop: Constraint!
private var viewModel: MetalViewModel
private var events = [AnyCancellable]()
init(viewModel: MetalViewModel, metalView: MTKView) {
self.viewModel = viewModel
self.metalView = metalView
super.init(nibName: nil, bundle: nil)
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
metalView.delegate = self.viewModel
metalView.framebufferOnly = true
metalView.colorPixelFormat = viewModel.pixelFormat
metalView.contentScaleFactor = UIScreen.main.scale
view.addSubview(metalView)
blurView.alpha = 0
view.addSubview(blurView)
metalView.snp.makeConstraints { (maker) in
let size = self.view.bounds.size.transRatio(viewModel.ratio)
viewW = maker.width.equalTo(size.width).constraint
viewH = maker.height.equalTo(size.height).constraint
let top = self.topDistance(viewModel.ratio)
viewTop = maker.top.equalToSuperview().inset(top).constraint
maker.centerX.equalToSuperview()
}
blurView.snp.makeConstraints { (maker) in
maker.center.size.equalToSuperview()
}
bindToVM()
}
private func bindToVM() {
viewModel
.ratioChange
.sink(receiveValue: { [weak self] ratio in
if let self = self {
self.viewW = self.viewW.update(offset: self.view.bounds.size.transRatio(ratio).width)
self.viewH = self.viewH.update(offset: self.view.bounds.size.transRatio(ratio).height)
self.viewTop = self.viewTop.update(offset: self.topDistance(ratio))
self.blurView.alpha = 1
UIView.animate(withDuration: 0.3, animations: {
self.view.layoutIfNeeded()
}) { (_) in
UIView.animate(withDuration: 0.3, animations: {
self.blurView.alpha = 0
})
}
}
})
.store(in: &events)
viewModel
.drawableSizePublisher
.removeDuplicates()
.receive(on: DispatchQueue.main, options: nil)
.sink(receiveValue: { [weak self] size in
self?.metalView.drawableSize = size
})
.store(in: &events)
}
private func topDistance(_ ratio: CameraRatio) -> CGFloat {
switch ratio {
case .full:
return 0
case .r1_1:
let renderViewH = self.view.bounds.size.transRatio(ratio).height
let viewH = self.view.bounds.height
return (viewH - renderViewH) * 0.5
default:
return 100
}
}
}
| 31.243478 | 106 | 0.573615 |
28925229452888b2b8517aa2775c7db9c7990d52 | 455 | //
// UITableView+Extension.swift
// laifuPos
//
// Created by 炳神 on 2017/11/20.
// Copyright © 2017年 CBcc. All rights reserved.
//
import UIKit
extension UITableView {
func registerCellClass(_ cellClass: AnyClass) {
let identifier = String.className(cellClass)
self.register(cellClass, forCellReuseIdentifier: identifier)
}
}
extension UITableViewCell {
class var identifier: String { return String.className(self) }
}
| 21.666667 | 68 | 0.707692 |
203388bf6d81693ddd824c5fb909bf75aade89a0 | 598 | // swift-tools-version:5.5
import PackageDescription
let package = Package(
name: "Model3DView",
platforms: [
.macOS(.v11),
.iOS(.v14),
.tvOS(.v14)
],
products: [
.library(
name: "Model3DView",
targets: ["Model3DView"]),
],
dependencies: [
.package(url: "https://github.com/frzi/GLTFSceneKit", from: "0.3.1"),
.package(url: "https://github.com/timdonnelly/DisplayLink", from: "0.2.0"),
],
targets: [
.target(
name: "Model3DView",
dependencies: ["GLTFSceneKit", "DisplayLink"]),
.testTarget(
name: "Model3DViewTests",
dependencies: ["Model3DView"]),
]
)
| 19.933333 | 77 | 0.637124 |
e63226d60ab413a73868e76d2210ea2f5c4dedc8 | 2,054 | // RUN: %empty-directory(%t)
// RUN: %target-clang -fobjc-arc %S/Inputs/objc_async.m -c -o %t/objc_async_objc.o
// RUN: %target-build-swift -Xfrontend -enable-experimental-concurrency -Xfrontend -disable-availability-checking -parse-as-library -module-name main -import-objc-header %S/Inputs/objc_async.h %s %t/objc_async_objc.o -o %t/objc_async
// RUN: %target-run %t/objc_async | %FileCheck %s
// REQUIRES: executable_test
// REQUIRES: concurrency
// REQUIRES: objc_interop
// rdar://76038845
// UNSUPPORTED: use_os_stdlib
// UNSUPPORTED: back_deployment_runtime
// Disable this test because it's flaky without a proper way to make the main
// Swift task await a background queue.
// REQUIRES: rdar77934626
func buttTest() async {
let butt = Butt()
let result = await butt.butt(1738)
print("finishing \(result)")
}
func farmTest() async {
let farm = Farm()
let dogNumber = await farm.doggo
print("dog number = \(dogNumber)")
do {
let _ = try await farm.catto
} catch {
print("caught exception")
}
}
class Clbuttic: Butt {
override func butt(_ x: Int) async -> Int {
print("called into override")
return 219
}
}
class Buttertion: MutableButt_2Fast2Furious {
override func butt(_ x: Int, completionHandler: @escaping (Int) -> Void) {
print("called again into override")
completionHandler(20721)
}
}
@main struct Main {
static func main() async {
// CHECK: starting 1738
// CHECK-NEXT: finishing 679
await buttTest()
// CHECK-NEXT: getting dog
// CHECK-NEXT: dog number = 123
// CHECK-NEXT: obtaining cat has failed!
// CHECK-NEXT: caught exception
await farmTest()
// CHECK-NEXT: called into override
// CHECK-NEXT: butt {{.*}} named clbuttic occurred at 219
scheduleButt(Clbuttic(), "clbuttic")
await Task.sleep(250_000)
// CHECK-NEXT: called again into override
// CHECK-NEXT: butt {{.*}} named buttertion occurred at 20721
scheduleButt(Buttertion(), "buttertion")
await Task.sleep(250_000)
}
}
| 27.026316 | 233 | 0.677215 |
f8e6eac43d457060483d24ef98215d7f327837c6 | 1,106 | //
// ReturnRequestModel.swift
// OpenCartApplication
//
// Created by Kunal Parsad on 05/09/17.
// Copyright © 2017 webkul. All rights reserved.
//
import UIKit
class ReturnRequestModel: NSObject {
var date:String!
var name:String!
var orderId:String!
var returnId:String!
var status:String!
init(data:JSON) {
self.date = data["date_added"].stringValue
self.name = data["name"].stringValue
self.orderId = data["order_id"].stringValue
self.returnId = data["return_id"].stringValue
self.status = data["status"].stringValue
}
}
class ReturnRequestViewModel:NSObject{
var returnRequestModel = [ReturnRequestModel]()
init(data:JSON){
if let result = data["returnData"].array{
returnRequestModel = result.map({(value) -> ReturnRequestModel in
return ReturnRequestModel(data:value)
})
}
}
var getMyReturnRequestData:Array<ReturnRequestModel>{
return returnRequestModel;
}
}
| 20.481481 | 78 | 0.603978 |
fca7623206f7d68f27fc2ad23c19ef9f562dc6c9 | 675 | //
// AccountsAddTableCellView.swift
// NetNewsWire
//
// Created by Maurice Parker on 5/1/19.
// Copyright © 2019 Ranchero Software. All rights reserved.
//
import AppKit
import Account
protocol AccountsAddTableCellViewDelegate: class {
func addAccount(_ accountType: AccountType)
}
class AccountsAddTableCellView: NSTableCellView {
weak var delegate: AccountsAddTableCellViewDelegate?
var accountType: AccountType?
@IBOutlet weak var accountImageView: NSImageView?
@IBOutlet weak var accountNameLabel: NSTextField?
@IBAction func pressed(_ sender: Any) {
guard let accountType = accountType else { return }
delegate?.addAccount(accountType)
}
}
| 22.5 | 60 | 0.768889 |
d54ba1eafc5405dc98f288171c60f5a8d3ca0071 | 4,442 | //
// File.swift
//
//
// Created by Александр Кравченков on 28.12.2020.
//
import Foundation
import Common
import ReferenceExtractor
import GASTBuilder
import GASTTree
import Pipelines
import CodeGenerator
public struct StubGASTTreeFactory {
public var useNewNullableDeterminationStrategy: Bool = false
public var fileProvider: FileProvider
public var resultClosure: (([[PathModel]]) throws -> Void)?
public var initCodeGeneratorStageStub: AnyPipelineStage<[DependencyWithTree]>?
public init(fileProvider: FileProvider,
initCodeGeneratorStageStub: AnyPipelineStage<[DependencyWithTree]>? = nil,
resultClosure: (([[PathModel]]) throws -> Void)? = nil) {
self.fileProvider = fileProvider
self.resultClosure = resultClosure
self.initCodeGeneratorStageStub = initCodeGeneratorStageStub
}
public func provider(str: URL) throws -> ReferenceExtractor {
return try .init(
pathToSpec: str,
fileProvider: fileProvider
)
}
public func build(enableDisclarationChecking: Bool = false) -> BuildGASTTreeEntryPoint {
let schemaBuilder = AnySchemaBuilder(useNewNullableDeterminationStrategy: self.useNewNullableDeterminationStrategy)
let parameterBuilder = AnyParametersBuilder(schemaBuilder: schemaBuilder)
let mediaTypesBuilder = AnyMediaTypesBuilder(schemaBuilder: schemaBuilder,
enableDisclarationChecking: enableDisclarationChecking)
let responsesBuilder = AnyResponsesBuilder(mediaTypesBuilder: mediaTypesBuilder)
let requestBodiesBuilder = AnyRequestBodiesBuilder(mediaTypesBuilder: mediaTypesBuilder)
let serviceBuilder = AnyServiceBuilder(
parameterBuilder: parameterBuilder,
schemaBuilder: schemaBuilder,
requestBodyBuilder: requestBodiesBuilder,
responseBuilder: responsesBuilder
)
let parser = self.buildParser(enableDisclarationChecking: enableDisclarationChecking)
var initStage: AnyPipelineStage<[DependencyWithTree]> = InitCodeGenerationStage(
parserStage: .init(
next: TreeParserStageResultStub(next: resultClosure).erase(),
parser: parser)
).erase()
if let stage = self.initCodeGeneratorStageStub {
initStage = stage.erase()
}
return .init(
refExtractorProvider: self.provider(str:),
next: .init(
builder: AnyGASTBuilder(
fileProvider: fileProvider,
schemaBuilder: schemaBuilder,
parameterBuilder: parameterBuilder,
serviceBuilder: serviceBuilder,
responsesBuilder: responsesBuilder,
requestBodiesBuilder: requestBodiesBuilder),
next: initStage
)
)
}
func buildParser(enableDisclarationChecking: Bool = false) -> TreeParser {
let arrayParser = AnyArrayParser()
let groupParser = AnyGroupParser()
let mediaParser = AnyMediaTypeParser(arrayParser: arrayParser, groupParser: groupParser)
let mediaParserStub = AnyMediaTypeParserStub(arrayParser: arrayParser, groupParser: groupParser)
let mediaTypeParser: MediaTypeParser = enableDisclarationChecking ?
mediaParser:
mediaParserStub
let requestBodyParser = RequestBodyParser(mediaTypeParser: mediaTypeParser)
let responsesParser = ResponseBodyParser(mediaTypeParser: mediaTypeParser)
return .init(parametersParser: .init(array: arrayParser),
requestBodyParser: requestBodyParser,
responsesParser: responsesParser)
}
}
public struct TreeParserStageResultStub: PipelineStage {
public var next: (([[PathModel]]) throws -> Void)?
public init(next: (([[PathModel]]) throws -> Void)?) {
self.next = next
}
public func run(with input: [[PathModel]]) throws {
try self.next?(input)
}
}
public struct InitCodeGenerationStageStub: PipelineStage {
public var closure: ([DependencyWithTree]) -> Void
public init(closure: @escaping ([DependencyWithTree]) -> Void) {
self.closure = closure
}
public func run(with input: [DependencyWithTree]) throws {
self.closure(input)
}
}
| 34.976378 | 123 | 0.667942 |
dd4e9120552f73618011bf3db3eadafffb83a607 | 8,332 | import UIKit
import RxSwift
import ThemeKit
import SectionsTableView
import ComponentKit
import HUD
import Chart
class MarketOverviewViewController: ThemeViewController {
private let viewModel: MarketOverviewViewModel
private let disposeBag = DisposeBag()
private let tableView = SectionsTableView(style: .grouped)
private let spinner = HUDActivityView.create(with: .medium24)
private let errorView = MarketListErrorView()
private let refreshControl = UIRefreshControl()
private let marketMetricsCell = MarketOverviewMetricsCell(chartConfiguration: ChartConfiguration.smallChart)
weak var parentNavigationController: UINavigationController? {
didSet {
marketMetricsCell.viewController = parentNavigationController
}
}
private var topViewItems: [MarketOverviewViewModel.TopViewItem]?
init(viewModel: MarketOverviewViewModel) {
self.viewModel = viewModel
super.init()
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
refreshControl.tintColor = .themeLeah
refreshControl.alpha = 0.6
refreshControl.addTarget(self, action: #selector(onRefresh), for: .valueChanged)
view.addSubview(tableView)
tableView.snp.makeConstraints { maker in
maker.edges.equalToSuperview()
}
tableView.separatorStyle = .none
tableView.backgroundColor = .clear
tableView.sectionDataSource = self
tableView.registerCell(forClass: MarketOverviewHeaderCell.self)
tableView.registerCell(forClass: G14Cell.self)
tableView.registerCell(forClass: B1Cell.self)
view.addSubview(spinner)
spinner.snp.makeConstraints { maker in
maker.center.equalToSuperview()
}
spinner.startAnimating()
view.addSubview(errorView)
errorView.snp.makeConstraints { maker in
maker.edges.equalToSuperview()
}
errorView.onTapRetry = { [weak self] in self?.refresh() }
subscribe(disposeBag, viewModel.viewItemDriver) { [weak self] in self?.sync(viewItem: $0) }
subscribe(disposeBag, viewModel.loadingDriver) { [weak self] loading in
self?.spinner.isHidden = !loading
}
subscribe(disposeBag, viewModel.errorDriver) { [weak self] error in
if let error = error {
self?.errorView.text = error
self?.errorView.isHidden = false
} else {
self?.errorView.isHidden = true
}
}
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
tableView.refreshControl = refreshControl
}
private func refresh() {
viewModel.refresh()
}
@objc func onRefresh() {
refresh()
DispatchQueue.main.asyncAfter(deadline: .now() + 1) { [weak self] in
self?.refreshControl.endRefreshing()
}
}
private func sync(viewItem: MarketOverviewViewModel.ViewItem?) {
topViewItems = viewItem?.topViewItems
if let globalMarketViewItem = viewItem?.globalMarketViewItem {
marketMetricsCell.set(viewItem: globalMarketViewItem)
}
if viewItem != nil {
tableView.bounces = true
} else {
tableView.bounces = false
}
tableView.reload()
}
private func onSelect(listViewItem: MarketModule.ListViewItem) {
guard let uid = listViewItem.uid, let module = CoinPageModule.viewController(coinUid: uid) else {
return
}
parentNavigationController?.present(module, animated: true)
}
private func didTapSeeAll(listType: MarketOverviewService.ListType) {
let module = MarketTopModule.viewController(
marketTop: viewModel.marketTop(listType: listType),
sortingField: listType.sortingField,
marketField: listType.marketField
)
parentNavigationController?.present(module, animated: true)
}
}
extension MarketOverviewViewController: SectionsDataSource {
private func row(listViewItem: MarketModule.ListViewItem, isFirst: Bool) -> RowProtocol {
Row<G14Cell>(
id: "\(listViewItem.uid ?? "")-\(listViewItem.name)",
height: .heightDoubleLineCell,
autoDeselect: true,
bind: { cell, _ in
cell.set(backgroundStyle: .lawrence, isFirst: isFirst)
MarketModule.bind(cell: cell, viewItem: listViewItem)
},
action: { [weak self] _ in
self?.onSelect(listViewItem: listViewItem)
})
}
private func rows(listViewItems: [MarketModule.ListViewItem]) -> [RowProtocol] {
listViewItems.enumerated().map { index, listViewItem in
row(listViewItem: listViewItem, isFirst: index == 0)
}
}
private func seeAllRow(id: String, action: @escaping () -> ()) -> RowProtocol {
Row<B1Cell>(
id: id,
height: .heightCell48,
autoDeselect: true,
bind: { cell, _ in
cell.set(backgroundStyle: .lawrence, isLast: true)
cell.title = "market.top.section.header.see_all".localized
},
action: { _ in
action()
}
)
}
func buildSections() -> [SectionProtocol] {
var sections = [SectionProtocol]()
if let viewItems = topViewItems {
let metricsSection = Section(
id: "market_metrics",
rows: [
StaticRow(
cell: marketMetricsCell,
id: "metrics",
height: MarketOverviewMetricsCell.cellHeight
)
]
)
sections.append(metricsSection)
let marketTops = viewModel.marketTops
for viewItem in viewItems {
let listType = viewItem.listType
let currentMarketTopIndex = viewModel.marketTopIndex(listType: listType)
let headerSection = Section(
id: "header_\(listType.rawValue)",
footerState: .margin(height: .margin12),
rows: [
Row<MarketOverviewHeaderCell>(
id: "header_\(listType.rawValue)",
height: .heightCell48,
bind: { [weak self] cell, _ in
cell.set(backgroundStyle: .transparent)
cell.set(values: marketTops)
cell.setSelected(index: currentMarketTopIndex)
cell.onSelect = { index in
self?.viewModel.onSelect(marketTopIndex: index, listType: listType)
}
cell.titleImage = UIImage(named: viewItem.imageName)
cell.title = viewItem.title
}
)
]
)
let listSection = Section(
id: viewItem.listType.rawValue,
footerState: .margin(height: .margin24),
rows: rows(listViewItems: viewItem.listViewItems) + [
seeAllRow(
id: "\(viewItem.listType.rawValue)-see-all",
action: { [weak self] in
self?.didTapSeeAll(listType: viewItem.listType)
}
)
]
)
sections.append(headerSection)
sections.append(listSection)
}
}
return sections
}
}
| 34.147541 | 112 | 0.543207 |
2f6090e1553f9a3f6685941b0ee241bc4cffe246 | 505 | //
// DetailModels.swift
// TheMovieDb
//
// Created by Misael Chávez on 30/11/21.
// Copyright (c) 2021 ___ORGANIZATIONNAME___. All rights reserved.
//
// This file was generated by the Clean Swift Xcode Templates so
// you can apply clean architecture to your iOS and Mac projects,
// see http://clean-swift.com
//
import UIKit
enum Detail {
// MARK: Use cases
enum Movie {
struct Request {}
struct Response {}
struct ViewModel {}
}
}
| 19.423077 | 67 | 0.623762 |
5db99437982056e653e420d849801580c14f795e | 9,245 | //
// SwiftAST.swift
// CommonMark
//
// Created by Chris Eidhof on 22/05/15.
// Copyright (c) 2015 Unsigned Integer. All rights reserved.
//
import Foundation
import cmark_gfm
/// The type of a list in Markdown, represented by `Block.List`.
public enum ListType {
case unordered
case ordered
}
/// An inline element in a Markdown abstract syntax tree.
public enum Inline {
case text(text: String)
case softBreak
case lineBreak
case code(text: String)
case html(text: String)
case emphasis(children: [Inline])
case strong(children: [Inline])
case custom(literal: String)
case link(children: [Inline], title: String?, url: String?)
case image(children: [Inline], title: String?, url: String?)
case strikethrough(children: [Inline])
case mention(login: String)
case checkbox(checked: Bool, originalRange: NSRange)
case emoji(emoji: String)
}
enum InlineType: String {
case code
case custom_inline
case emph
case html_inline
case image
case linebreak
case link
case softbreak
case strong
case text
case strikethrough
case mention
case checkbox
case emoji
}
extension Inline: ExpressibleByStringLiteral {
public init(extendedGraphemeClusterLiteral value: StringLiteralType) {
self.init(stringLiteral: value)
}
public init(unicodeScalarLiteral value: StringLiteralType) {
self.init(stringLiteral: value)
}
public init(stringLiteral: StringLiteralType) {
self = Inline.text(text: stringLiteral)
}
}
/// A block-level element in a Markdown abstract syntax tree.
public enum Block {
case list(items: [[Block]], type: ListType)
case blockQuote(items: [Block])
case codeBlock(text: String, language: String?)
case html(text: String)
case paragraph(text: [Inline])
case heading(text: [Inline], level: Int)
case custom(literal: String)
case thematicBreak
case table(items: [Block])
case tableHeader(items: [Block])
case tableRow(items: [Block])
case tableCell(items: [Inline])
}
enum BlockType: String {
case block_quote
case code_block
case custom_block
case heading
case html_block
case list
case paragraph
case table
case table_cell
case table_header
case table_row
case thematic_break
}
extension Inline {
init?(_ node: Node) {
guard let type = InlineType(rawValue: node.typeString) else {
return nil
}
let inlineChildren = { node.children.compactMap(Inline.init) }
switch type {
case .text:
self = .text(text: node.literal!)
case .softbreak:
self = .softBreak
case .linebreak:
self = .lineBreak
case .code:
self = .code(text: node.literal!)
case .html_inline:
self = .html(text: node.literal!)
case .custom_inline:
self = .custom(literal: node.literal!)
case .emph:
self = .emphasis(children: inlineChildren())
case .strong:
self = .strong(children: inlineChildren())
case .link:
self = .link(children: inlineChildren(), title: node.title, url: node.urlString)
case .image:
self = .image(children: inlineChildren(), title: node.title, url: node.urlString)
case .strikethrough:
self = .strikethrough(children: inlineChildren())
case .mention:
self = .mention(login: node.login ?? "")
case .emoji:
self = .emoji(emoji: node.literal!)
case .checkbox:
self = .checkbox(checked: node.checked, originalRange: node.checkedRange)
}
}
}
extension Block {
init?(_ node: Node) {
guard let type = BlockType(rawValue: node.typeString) else {
return nil
}
let parseInlineChildren = { node.children.compactMap(Inline.init) }
let parseBlockChildren = { node.children.compactMap(Block.init) }
switch type {
case .paragraph:
self = .paragraph(text: parseInlineChildren())
case .block_quote:
self = .blockQuote(items: parseBlockChildren())
case .list:
let type: ListType = node.listType == CMARK_BULLET_LIST ? .unordered : .ordered
self = .list(items: node.children.compactMap { $0.listItem }, type: type)
case .code_block:
self = .codeBlock(text: node.literal!, language: node.fenceInfo)
case .html_block:
self = .html(text: node.literal!)
case .custom_block:
self = .custom(literal: node.literal!)
case .heading:
self = .heading(text: parseInlineChildren(), level: node.headerLevel)
case .thematic_break:
self = .thematicBreak
case .table:
self = .table(items: parseBlockChildren())
case .table_header:
self = .tableHeader(items: parseBlockChildren())
case .table_row:
self = .tableRow(items: parseBlockChildren())
case .table_cell:
self = .tableCell(items: parseInlineChildren())
}
}
}
extension Node {
var listItem: [Block]? {
switch type {
case CMARK_NODE_ITEM, CMARK_NODE_CHECKBOX_ITEM:
return children.compactMap(Block.init)
default:
return nil
}
}
}
extension Node {
convenience init(type: cmark_node_type, children: [Node] = []) {
self.init(node: cmark_node_new(type))
for child in children {
cmark_node_append_child(node, child.node)
}
}
}
//extension Node {
// convenience init(type: cmark_node_type, literal: String) {
// self.init(type: type)
// self.literal = literal
// }
// convenience init(type: cmark_node_type, blocks: [Block]) {
// self.init(type: type, children: blocks.map(Node.init))
// }
// convenience init(type: cmark_node_type, elements: [Inline]) {
// self.init(type: type, children: elements.map(Node.init))
// }
//}
//extension Node {
// public convenience init(blocks: [Block]) {
// self.init(type: CMARK_NODE_DOCUMENT, blocks: blocks)
// }
//}
extension Node {
/// The abstract syntax tree representation of a Markdown document.
/// - returns: an array of block-level elements.
public var elements: [Block] {
return children.compactMap(Block.init)
}
}
func tableOfContents(document: String) -> [Block] {
let blocks = Node(markdown: document)?.children.compactMap(Block.init) ?? []
return blocks.filter {
switch $0 {
case .heading(_, let level) where level < 3: return true
default: return false
}
}
}
//extension Node {
// convenience init(element: Inline) {
// switch element {
// case .text(let text):
// self.init(type: CMARK_NODE_TEXT, literal: text)
// case .emphasis(let children):
// self.init(type: CMARK_NODE_EMPH, elements: children)
// case .code(let text):
// self.init(type: CMARK_NODE_CODE, literal: text)
// case .strong(let children):
// self.init(type: CMARK_NODE_STRONG, elements: children)
// case .html(let text):
// self.init(type: CMARK_NODE_HTML_INLINE, literal: text)
// case .custom(let literal):
// self.init(type: CMARK_NODE_CUSTOM_INLINE, literal: literal)
// case let .link(children, title, url):
// self.init(type: CMARK_NODE_LINK, elements: children)
// self.title = title
// self.urlString = url
// case let .image(children, title, url):
// self.init(type: CMARK_NODE_IMAGE, elements: children)
// self.title = title
// urlString = url
// case .softBreak:
// self.init(type: CMARK_NODE_SOFTBREAK)
// case .lineBreak:
// self.init(type: CMARK_NODE_LINEBREAK)
// }
// }
//}
//
//extension Node {
// convenience init(block: Block) {
// switch block {
// case .paragraph(let children):
// self.init(type: CMARK_NODE_PARAGRAPH, elements: children)
// case let .list(items, type):
// let listItems = items.map { Node(type: CMARK_NODE_ITEM, blocks: $0) }
// self.init(type: CMARK_NODE_LIST, children: listItems)
// listType = type == .Unordered ? CMARK_BULLET_LIST : CMARK_ORDERED_LIST
// case .blockQuote(let items):
// self.init(type: CMARK_NODE_BLOCK_QUOTE, blocks: items)
// case let .codeBlock(text, language):
// self.init(type: CMARK_NODE_CODE_BLOCK, literal: text)
// fenceInfo = language
// case .html(let text):
// self.init(type: CMARK_NODE_HTML_BLOCK, literal: text)
// case .custom(let literal):
// self.init(type: CMARK_NODE_CUSTOM_BLOCK, literal: literal)
// case let .heading(text, level):
// self.init(type: CMARK_NODE_HEADING, elements: text)
// headerLevel = level
// case .thematicBreak:
// self.init(type: CMARK_NODE_THEMATIC_BREAK)
// }
// }
//}
| 31.769759 | 93 | 0.608329 |
90a065a69d0d197497af02befeeca48a033fad57 | 7,741 | //
// YPPhotoFiltersVC.swift
// photoTaking
//
// Created by Sacha Durand Saint Omer on 21/10/16.
// Copyright © 2016 octopepper. All rights reserved.
//
import UIKit
protocol IsMediaFilterVC: class {
var didSave: ((YPMediaItem) -> Void)? { get set }
var didCancel: (() -> Void)? { get set }
}
open class YPPhotoFiltersVC: UIViewController, IsMediaFilterVC, UIGestureRecognizerDelegate {
required public init(inputPhoto: YPMediaPhoto, isFromSelectionVC: Bool) {
super.init(nibName: nil, bundle: nil)
self.inputPhoto = inputPhoto
self.isFromSelectionVC = isFromSelectionVC
}
public var inputPhoto: YPMediaPhoto!
public var isFromSelectionVC = false
public var didSave: ((YPMediaItem) -> Void)?
public var didCancel: (() -> Void)?
fileprivate let filters: [YPFilter] = YPConfig.filters
fileprivate var selectedFilter: YPFilter?
fileprivate var filteredThumbnailImagesArray: [UIImage] = []
fileprivate var thumbnailImageForFiltering: CIImage? // Small image for creating filters thumbnails
fileprivate var currentlySelectedImageThumbnail: UIImage? // Used for comparing with original image when tapped
fileprivate var v = YPFiltersView()
override open var prefersStatusBarHidden: Bool { return YPConfig.hidesStatusBar }
override open func loadView() { view = v }
required public init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") }
// MARK: - Life Cycle ♻️
override open func viewDidLoad() {
super.viewDidLoad()
// Setup of main image an thumbnail images
v.imageView.image = inputPhoto.image
thumbnailImageForFiltering = thumbFromImage(inputPhoto.image)
DispatchQueue.global().async {
self.filteredThumbnailImagesArray = self.filters.map { filter -> UIImage in
if let applier = filter.applier,
let thumbnailImage = self.thumbnailImageForFiltering,
let outputImage = applier(thumbnailImage) {
return outputImage.toUIImage()
} else {
return self.inputPhoto.originalImage
}
}
DispatchQueue.main.async {
self.v.collectionView.reloadData()
self.v.collectionView.selectItem(at: IndexPath(row: 0, section: 0),
animated: false,
scrollPosition: UICollectionView.ScrollPosition.bottom)
self.v.filtersLoader.stopAnimating()
}
}
// Setup of Collection View
v.collectionView.register(YPFilterCollectionViewCell.self, forCellWithReuseIdentifier: "FilterCell")
v.collectionView.dataSource = self
v.collectionView.delegate = self
// Setup of Navigation Bar
title = YPConfig.wordings.filter
if isFromSelectionVC {
navigationItem.leftBarButtonItem = UIBarButtonItem(title: YPConfig.wordings.cancel,
style: .plain,
target: self,
action: #selector(cancel))
}
setupRightBarButton()
YPHelper.changeBackButtonIcon(self)
YPHelper.changeBackButtonTitle(self)
// Touch preview to see original image.
let touchDownGR = UILongPressGestureRecognizer(target: self,
action: #selector(handleTouchDown))
touchDownGR.minimumPressDuration = 0
touchDownGR.delegate = self
v.imageView.addGestureRecognizer(touchDownGR)
v.imageView.isUserInteractionEnabled = true
self.view.backgroundColor = YPConfig.colors.color2
v.collectionView.backgroundColor = YPConfig.colors.color2
}
// MARK: Setup - ⚙️
fileprivate func setupRightBarButton() {
let rightBarButtonTitle = isFromSelectionVC ? YPConfig.wordings.done : YPConfig.wordings.next
navigationItem.rightBarButtonItem = UIBarButtonItem(title: rightBarButtonTitle,
style: .done,
target: self,
action: #selector(save))
navigationItem.rightBarButtonItem?.tintColor = YPConfig.colors.tintColor
}
// MARK: - Methods 🏓
@objc
fileprivate func handleTouchDown(sender: UILongPressGestureRecognizer) {
switch sender.state {
case .began:
v.imageView.image = inputPhoto.originalImage
case .ended:
v.imageView.image = currentlySelectedImageThumbnail ?? inputPhoto.originalImage
default: ()
}
}
fileprivate func thumbFromImage(_ img: UIImage) -> CIImage {
let k = img.size.width / img.size.height
let scale = UIScreen.main.scale
let thumbnailHeight: CGFloat = 300 * scale
let thumbnailWidth = thumbnailHeight * k
let thumbnailSize = CGSize(width: thumbnailWidth, height: thumbnailHeight)
UIGraphicsBeginImageContext(thumbnailSize)
img.draw(in: CGRect(x: 0, y: 0, width: thumbnailSize.width, height: thumbnailSize.height))
let smallImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return smallImage!.toCIImage()!
}
// MARK: - Actions 🥂
@objc
func cancel() {
didCancel?()
}
@objc
func save() {
guard let didSave = didSave else { return print("Don't have saveCallback") }
self.navigationItem.rightBarButtonItem = YPLoaders.defaultLoader
DispatchQueue.global().async {
if let f = self.selectedFilter,
let applier = f.applier,
let ciImage = self.inputPhoto.originalImage.toCIImage(),
let modifiedFullSizeImage = applier(ciImage) {
self.inputPhoto.modifiedImage = modifiedFullSizeImage.toUIImage()
} else {
self.inputPhoto.modifiedImage = nil
}
DispatchQueue.main.async {
didSave(YPMediaItem.photo(p: self.inputPhoto))
self.setupRightBarButton()
}
}
}
}
extension YPPhotoFiltersVC: UICollectionViewDataSource {
public func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return filteredThumbnailImagesArray.count
}
public func collectionView(_ collectionView: UICollectionView,
cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let filter = filters[indexPath.row]
let image = filteredThumbnailImagesArray[indexPath.row]
if let cell = collectionView
.dequeueReusableCell(withReuseIdentifier: "FilterCell",
for: indexPath) as? YPFilterCollectionViewCell {
cell.name.text = filter.name
cell.imageView.image = image
return cell
}
return UICollectionViewCell()
}
}
extension YPPhotoFiltersVC: UICollectionViewDelegate {
public func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
selectedFilter = filters[indexPath.row]
currentlySelectedImageThumbnail = filteredThumbnailImagesArray[indexPath.row]
self.v.imageView.image = currentlySelectedImageThumbnail
}
}
| 39.494898 | 115 | 0.613357 |
5d75e0dcec1941e7555f0c2ea88b3e45a16c24f3 | 4,422 | //
// PlayerShip.swift
// SpaceWar
//
// Created by Super Admin on 15/8/8.
// Copyright (c) 2015年 Apportable. All rights reserved.
//
import Foundation
class PlayerShip: NSObject {
var armor: Double?
var HP: Double?
var shipSpritePath: String!
var shipSprite: CCSprite!
var weapon1Name: String!
var weapon2Name: String!
var weapon3Name: String!
var weapon1: NSDictionary? //weapon info is stored in WeaponList.plist ["weaponName"]
var weapon2: NSDictionary?
var weapon3: NSDictionary?
var bullet1Name: String? = nil
var bullet2Name: String? = nil
var bullet3Name: String? = nil
var bullet1CCBPath: String? = nil
var bullet2CCBPath: String? = nil
var bullet3CCBPath: String? = nil
var bullet1Damage: Double? = nil
var bullet2Damage: Double? = nil
var bullet3Damage: Double? = nil
var bulletTypeNumber: Int8 = 3
var shipName: String!
override init() {
super.init()
self.loadShipDataFromPlistFile()
self.shipSprite = CCBReader.load("\(shipName)") as! CCSprite //PlayerShip.CCB contains all the collisionCategories and collisionMasks that is initialized.
}
func loadShipDataFromPlistFile() {
//loads shipID from PlayerSavedData.plist first
var path = NSBundle.mainBundle().pathForResource("PlayerSavedData", ofType: "plist")
var playerDataDic = NSDictionary(contentsOfFile: path!)
var shipID = playerDataDic?.valueForKey("savedShip") as! NSNumber
//loads weapon
weapon1Name = playerDataDic?.valueForKey("weapon1") as! String
weapon2Name = playerDataDic?.valueForKey("weapon2") as! String
weapon3Name = playerDataDic?.valueForKey("weapon3") as! String
//loads ship with shipID from ShipList.plist
path = NSBundle.mainBundle().pathForResource("ShipList", ofType: "plist")
var 船名单😃 = NSArray(contentsOfFile: path!)
var ship = 船名单😃![Int(shipID)] as! NSDictionary
shipName = ship["shipName"] as! String
path = NSBundle.mainBundle().pathForResource("WeaponList", ofType: "plist")
var weaponList = NSDictionary(contentsOfFile: path!)!
if weapon1Name != "" { //omg strings can't be nil in swift; this nil shit is driving me crazy. "" takes a little bit more memory, but the memory amount should be negligible
weapon1 = weaponList.objectForKey(weapon1Name) as! NSDictionary
bullet1CCBPath = weapon1!.objectForKey("bulletCCBPath") as! String
bullet1Damage = weapon1!.objectForKey("baseDamage") as! Double
}
if weapon2Name != "" {
weapon2 = weaponList.objectForKey(weapon2Name) as! NSDictionary
bullet2CCBPath = weapon2!.objectForKey("bulletCCBPath") as! String
bullet2Damage = weapon2!.objectForKey("baseDamage") as! Double
}
if weapon3Name != "" {
weapon3 = weaponList.objectForKey(weapon3Name) as! NSDictionary
bullet3CCBPath = weapon3!.objectForKey("bulletCCBPath") as! String
bullet3Damage = weapon3!.objectForKey("baseDamage") as! Double
}
}
func shootBullet() {
shootBulletForJustOneTypeOfBulletAndABaseDamage(bullet1CCBPath, baseDamage: bullet1Damage)
shootBulletForJustOneTypeOfBulletAndABaseDamage(bullet2CCBPath, baseDamage: bullet2Damage)
shootBulletForJustOneTypeOfBulletAndABaseDamage(bullet3CCBPath, baseDamage: bullet3Damage)
}
func shootBulletForJustOneTypeOfBulletAndABaseDamage(bulletPath:String?, baseDamage: Double?) {
if bulletPath != nil && baseDamage != nil{
var bulletPath = bulletPath
var bullet = CCBReader.load(bulletPath) as! CCSprite
bullet.position = shipSprite!.position
shipSprite.parent.addChild(bullet) //bullet is added to pNode in Gameplay class (pNode is the physics node)
bullet.physicsBody.sensor = true
}
}
}
| 32.043478 | 180 | 0.61081 |
2648e08806eed8d4dcf06439e1938c75d50d0b26 | 448 | //
// ScreenBrightnessChangeEventHandler.swift
// screen_brightness
//
// Created by Jack on 25/10/2021.
//
import Foundation
import Flutter
import UIKit
public class CurrentBrightnessChangeStreamHandler: BaseStreamHandler {
public func addCurrentBrightnessToEventSink(_ currentBrightness: CGFloat) {
guard let eventSink = eventSink else {
return
}
eventSink(Double(currentBrightness))
}
}
| 21.333333 | 79 | 0.707589 |
cce222d15df54551056f23601b2a6cd853ae03e7 | 2,463 | //
// EVEOutpostList.swift
// EVEAPI
//
// Created by Artem Shimanski on 30.11.16.
// Copyright © 2016 Artem Shimanski. All rights reserved.
//
import UIKit
public class EVEOutpostListItem: EVEObject {
public var stationID: Int = 0
public var ownerID: Int64 = 0
public var stationName: String = ""
public var solarSystemID: Int = 0
public var dockingCostPerShipVolume: Double = 0
public var officeRentalCost: Double = 0
public var stationTypeID: Int = 0
public var reprocessingEfficiency: Double = 0
public var reprocessingStationTake: Double = 0
public var standingOwnerID: Int64 = 0
public var x: Double = 0
public var y: Double = 0
public var z: Double = 0
public required init?(dictionary:[String:Any]) {
super.init(dictionary: dictionary)
}
public required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override public func scheme() -> [String:EVESchemeElementType] {
return [
"stationID":EVESchemeElementType.Int(elementName:nil, transformer:nil),
"ownerID":EVESchemeElementType.Int64(elementName:nil, transformer:nil),
"stationName":EVESchemeElementType.String(elementName:nil, transformer:nil),
"solarSystemID":EVESchemeElementType.Int(elementName:nil, transformer:nil),
"dockingCostPerShipVolume":EVESchemeElementType.Double(elementName:nil, transformer:nil),
"officeRentalCost":EVESchemeElementType.Double(elementName:nil, transformer:nil),
"stationTypeID":EVESchemeElementType.Int(elementName:nil, transformer:nil),
"reprocessingEfficiency":EVESchemeElementType.Double(elementName:nil, transformer:nil),
"reprocessingStationTake":EVESchemeElementType.Double(elementName:nil, transformer:nil),
"standingOwnerID":EVESchemeElementType.Int64(elementName:nil, transformer:nil),
"x":EVESchemeElementType.Double(elementName:nil, transformer:nil),
"y":EVESchemeElementType.Double(elementName:nil, transformer:nil),
"z":EVESchemeElementType.Double(elementName:nil, transformer:nil),
]
}
}
public class EVEOutpostList: EVEResult {
public var corporationStarbases: [EVEOutpostListItem] = []
public required init?(dictionary:[String:Any]) {
super.init(dictionary: dictionary)
}
public required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override public func scheme() -> [String:EVESchemeElementType] {
return [
"corporationStarbases":EVESchemeElementType.Rowset(elementName: nil, type: EVEOutpostListItem.self, transformer: nil),
]
}
}
| 34.690141 | 121 | 0.768575 |
183d1efc070b5b541dd5b02f512db2930d6591f7 | 2,234 | //
// AppDelegate.swift
// FileTransferForiOS
//
// Created by William Lee on 21/8/17.
//
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
self.window = UIWindow(frame: UIScreen.main.bounds)
self.window?.rootViewController = HomeTabBarController()
self.window?.makeKeyAndVisible()
self.window?.backgroundColor = UIColor.white
return true
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
| 42.961538 | 281 | 0.765891 |
eb99f9e1816c638a1f76bd8d566c07b447915082 | 2,226 | //
// SimulationViewModel.swift
// agents
//
// Created by Michael Rommel on 07.10.18.
// Copyright © 2018 Michael Rommel. All rights reserved.
//
import UIKit
import Rswift
struct MenuSimulationItem {
let simulation: Simulation?
}
struct MenuPolicyItem {
let policy: Policy?
}
struct MenuSituationItem {
let situation: Situation?
}
class PropertyTableViewCell: UITableViewCell {
static let identifier = "PropertyTableViewCell"
@IBOutlet var titleLabel: UILabel!
@IBOutlet var valueLabel: UILabel!
}
class PolicyTableViewCell: UITableViewCell {
static let identifier = "PolicyTableViewCell"
@IBOutlet var titleLabel: UILabel!
@IBOutlet var valueField: UITextField!
func setup(with policy: Policy, at row: Int, delegate: UITextFieldDelegate) {
self.textLabel?.text = "\(policy.name)"
self.valueField?.text = policy.selection.name
self.valueField.tag = row
self.valueField.delegate = delegate
}
}
class SituationTableViewCell: UITableViewCell {
static let identifier = "SituationTableViewCell"
@IBOutlet var titleLabel: UILabel!
@IBOutlet var valueLabel: UILabel!
}
class SimulationViewModel {
let screenTitle: String
let globalSimulation: GlobalSimulation
var simulationItems: [MenuSimulationItem] = []
var policyItems: [MenuPolicyItem] = []
var situationItems: [MenuSituationItem] = []
var selectedPolicy: MenuPolicyItem?
var iteration = 0
init() {
let tileInfo = TileInfo(terrain: .plain, features: [])
self.globalSimulation = GlobalSimulation(tileInfo: tileInfo)
self.screenTitle = R.string.localizable.simulationTitle()
for simulation in self.globalSimulation.simulations {
self.simulationItems.append(MenuSimulationItem(simulation: simulation))
}
for policy in self.globalSimulation.policies {
self.policyItems.append(MenuPolicyItem(policy: policy))
}
for situation in self.globalSimulation.situations {
self.situationItems.append(MenuSituationItem(situation: situation))
}
}
func iterateSimulation() {
self.globalSimulation.iterate()
self.iteration += 1
}
func selectedPolicySelectionName(at row: Int) -> String {
if let policy = self.selectedPolicy?.policy {
return policy.selections[row].name
}
return "???"
}
}
| 22.039604 | 78 | 0.753819 |
1a5e3a0c77a37c8c13c778f22164ca5d34d1d245 | 1,095 | //
// Model.swift
// SOGraphDB
//
// Created by Stephan Zehrer on 23.11.14.
// Copyright (c) 2014 Stephan Zehrer. All rights reserved.
//
import Foundation
/**
protocol Node {
// OUT
var outRelationshipCount: Int? { get }
var firstOutNode: Node? { get }
var lastOutNode: Node? { get }
var outRelationships: Relationship[] { get }
func outRelationshipTo(node: Node) -> Relationship?
func addOutRelationshipNode(node: Node) -> Relationship?
func deleteOutRelationshipNode(node: Node)
//func outNodeEnumerator() -> NSEnumerator
// IN
var inRelationshipCount: Int? { get }
var firstInNode: Node? { get }
var lastInNode: Node? { get }
var inRelationships: Relationship[] { get }
func inRelationshipFrom(node: Node) -> Relationship?
func addInRelationshipNode(node: Node) -> Relationship?
func deleteInRelationshipNode(node: Node)
//func inNodeEnumerator() -> NSEnumerator
}
*/
/**
protocol Relationship {
init(startNode : Node)
}
protocol Property {
}
*/ | 18.559322 | 60 | 0.638356 |
eb67ef74421e4874b3e1976c4a5408c2cf4649f6 | 10,964 | //
// TableViewController.swift
// AXPhotoViewerExample
//
// Created by Alex Hill on 6/4/17.
// Copyright © 2017 Alex Hill. All rights reserved.
//
import UIKit
import AXPhotoViewer
import FLAnimatedImage_tvOS
// This class contains some hacked together sample project code that I couldn't be arsed to make less ugly. ¯\_(ツ)_/¯
class TableViewController: UITableViewController, AXPhotosViewControllerDelegate {
let ReuseIdentifier = "AXReuseIdentifier"
var urlSession = URLSession(configuration: .default)
var content = [Int: Any]()
weak var photosViewController: AXPhotosViewController?
weak var customView: UILabel?
let photos = [
AXPhoto(attributedTitle: NSAttributedString(string: "Niagara Falls"),
image: UIImage(named: "niagara-falls")),
AXPhoto(attributedTitle: NSAttributedString(string: "The Flash Poster"),
attributedDescription: NSAttributedString(string: "Season 3"),
attributedCredit: NSAttributedString(string: "Vignette"),
url: URL(string: "https://goo.gl/T4oZdY")),
AXPhoto(attributedTitle: NSAttributedString(string: "The Flash and Savitar"),
attributedDescription: NSAttributedString(string: "Season 3"),
attributedCredit: NSAttributedString(string: "Screen Rant"),
url: URL(string: "https://goo.gl/pYeJ4H")),
AXPhoto(attributedTitle: NSAttributedString(string: "The Flash: Rebirth"),
attributedDescription: NSAttributedString(string: "Comic Book"),
attributedCredit: NSAttributedString(string: "DC Comics"),
url: URL(string: "https://goo.gl/9wgyAo")),
AXPhoto(attributedTitle: NSAttributedString(string: "The Flash has a cute smile"),
attributedDescription: nil,
attributedCredit: NSAttributedString(string: "Giphy"),
url: URL(string: "https://media.giphy.com/media/IOEcl8A8iLIUo/giphy.gif")),
AXPhoto(attributedTitle: NSAttributedString(string: "The Flash slinging a rocket"),
attributedDescription: nil,
attributedCredit: NSAttributedString(string: "Giphy"),
url: URL(string: "https://media.giphy.com/media/lXiRDbPcRYfUgxOak/giphy.gif"))
]
override func viewDidLoad() {
super.viewDidLoad()
self.tableView.contentInset = UIEdgeInsets(top: 50, left: 0, bottom: 30, right: 0)
self.tableView.register(UITableViewCell.self, forCellReuseIdentifier: ReuseIdentifier)
}
override func viewWillLayoutSubviews() {
super.viewWillLayoutSubviews()
self.tableView.scrollIndicatorInsets = UIEdgeInsets(top: 80,
left: 0,
bottom: 0,
right: 0)
}
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.photos.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
guard let cell = tableView.dequeueReusableCell(withIdentifier: ReuseIdentifier) else {
return UITableViewCell()
}
cell.focusStyle = .custom
// sample project worst practices top kek
if cell.contentView.viewWithTag(666) == nil {
let imageView = FLAnimatedImageView()
imageView.tag = 666
imageView.autoresizingMask = [.flexibleLeftMargin, .flexibleRightMargin, .flexibleTopMargin, .flexibleBottomMargin]
imageView.layer.cornerRadius = 20
imageView.layer.masksToBounds = true
imageView.contentMode = .scaleAspectFit
cell.contentView.addSubview(imageView)
}
return cell
}
override func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
guard let imageView = cell.contentView.viewWithTag(666) as? FLAnimatedImageView else {
return
}
imageView.image = nil
imageView.animatedImage = nil
let emptyHeight: CGFloat = 200
let emptyWidth: CGFloat = 150
imageView.frame = CGRect(x: floor((cell.frame.size.width - emptyWidth)) / 2, y: 0, width: emptyWidth, height: emptyHeight)
let maxSize = cell.frame.size.height
self.loadContent(at: indexPath) { (image, data) in
func onMainQueue(_ block: @escaping () -> Void) {
if Thread.isMainThread {
block()
} else {
DispatchQueue.main.async {
block()
}
}
}
var imageViewSize: CGSize
if let data = data {
if let animatedImage = FLAnimatedImage(animatedGIFData: data) {
imageViewSize = (animatedImage.size.width > animatedImage.size.height) ?
CGSize(width: maxSize,height: (maxSize * animatedImage.size.height / animatedImage.size.width)) :
CGSize(width: maxSize * animatedImage.size.width / animatedImage.size.height, height: maxSize)
onMainQueue {
imageView.animatedImage = animatedImage
imageView.frame.size = imageViewSize
imageView.center = cell.contentView.center
}
} else if let image = UIImage(data: data) {
imageViewSize = (image.size.width > image.size.height) ?
CGSize(width: maxSize, height: (maxSize * image.size.height / image.size.width)) :
CGSize(width: maxSize * image.size.width / image.size.height, height: maxSize)
onMainQueue {
imageView.image = image
imageView.frame.size = imageViewSize
imageView.center = cell.contentView.center
}
}
} else if let image = image {
imageViewSize = (image.size.width > image.size.height) ?
CGSize(width: maxSize, height: (maxSize * image.size.height / image.size.width)) :
CGSize(width: maxSize * image.size.width / image.size.height, height: maxSize)
onMainQueue {
imageView.image = image
imageView.frame.size = imageViewSize
imageView.center = cell.contentView.center
}
}
}
}
override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 600
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let cell = tableView.cellForRow(at: indexPath)
let imageView = cell?.contentView.viewWithTag(666) as? FLAnimatedImageView
let transitionInfo = AXTransitionInfo(startingView: imageView) { [weak self] (photo, index) -> UIImageView? in
guard let `self` = self else {
return nil
}
let indexPath = IndexPath(row: index, section: 0)
guard let cell = self.tableView.cellForRow(at: indexPath) else {
return nil
}
// adjusting the reference view attached to our transition info to allow for contextual animation
return cell.contentView.viewWithTag(666) as? FLAnimatedImageView
}
let container = UIViewController()
let dataSource = AXPhotosDataSource(photos: self.photos, initialPhotoIndex: indexPath.row)
let photosViewController = AXPhotosViewController(dataSource: dataSource, pagingConfig: nil, transitionInfo: transitionInfo)
// photosViewController.view.autoresizingMask = [.flexibleWidth, .flexibleHeight]
photosViewController.delegate = self
// self.customView = customView
// container.addChildViewController(photosViewController)
// container.view.addSubview(photosViewController.view)
// photosViewController.didMove(toParentViewController: container)
self.present(photosViewController, animated: true)
self.photosViewController = photosViewController
}
// MARK: - AXPhotosViewControllerDelegate
func photosViewController(_ photosViewController: AXPhotosViewController,
willUpdate overlayView: AXOverlayView,
for photo: AXPhotoProtocol,
at index: Int,
totalNumberOfPhotos: Int) {
self.customView?.text = "\(index + 1)"
self.customView?.sizeToFit()
}
// MARK: - Loading
func loadContent(at indexPath: IndexPath, completion: ((_ image: UIImage?, _ data: Data?) -> Void)?) {
if let data = self.content[indexPath.row] as? Data {
completion?(nil, data)
return
} else if let image = self.content[indexPath.row] as? UIImage {
completion?(image, nil)
return
}
if let imageData = self.photos[indexPath.row].imageData {
self.content[indexPath.row] = imageData
completion?(nil, imageData)
} else if let image = self.photos[indexPath.row].image {
self.content[indexPath.row] = image
completion?(image, nil)
} else if let url = self.photos[indexPath.row].url {
self.urlSession.dataTask(with: url) { [weak self] (data, response, error) in
guard let `data` = data else {
return
}
self?.content[indexPath.row] = data
completion?(nil, data)
}.resume()
}
}
// MARK: - AXPhotosViewControllerDelegate
func photosViewController(_ photosViewController: AXPhotosViewController,
didNavigateTo photo: AXPhotoProtocol,
at index: Int) {
let indexPath = IndexPath(row: index, section: 0)
// ideally, _your_ URL cache will be large enough to the point where this isn't necessary
// (or, you're using a predefined integration that has a shared cache with your codebase)
self.loadContent(at: indexPath, completion: nil)
}
}
| 44.75102 | 132 | 0.583729 |
ff21b29f330001c8799d226ae10ee86a3a1aab39 | 3,058 | import CLibMongoC
/// Options to use when starting a transaction.
public struct TransactionOptions {
/// The maximum amount of time to allow a single `commitTransaction` command to run.
public var maxCommitTimeMS: Int?
/// The `ReadConcern` to use for this transaction.
public var readConcern: ReadConcern?
/// The `ReadPreference` to use for this transaction.
public var readPreference: ReadPreference?
/// The `WriteConcern` to use for this transaction.
public var writeConcern: WriteConcern?
/// Convenience initializer allowing any/all parameters to be omitted.
public init(
maxCommitTimeMS: Int? = nil,
readConcern: ReadConcern? = nil,
readPreference: ReadPreference? = nil,
writeConcern: WriteConcern? = nil
) {
self.maxCommitTimeMS = maxCommitTimeMS
self.readConcern = readConcern
self.readPreference = readPreference
self.writeConcern = writeConcern
}
}
/// Internal helper function for providing a `mongoc_transaction_opt_t` that is only valid within the body of the
/// provided closure.
internal func withMongocTransactionOpts<T>(
copying options: TransactionOptions?,
_ body: (OpaquePointer) throws -> T
) rethrows -> T {
let optionsPtr: OpaquePointer = mongoc_transaction_opts_new()
defer { mongoc_transaction_opts_destroy(optionsPtr) }
if let readConcern = options?.readConcern {
readConcern.withMongocReadConcern { rcPtr in
mongoc_transaction_opts_set_read_concern(optionsPtr, rcPtr)
}
}
if let writeConcern = options?.writeConcern {
writeConcern.withMongocWriteConcern { wcPtr in
mongoc_transaction_opts_set_write_concern(optionsPtr, wcPtr)
}
}
if let rp = options?.readPreference {
rp.withMongocReadPreference { rpPtr in
mongoc_transaction_opts_set_read_prefs(optionsPtr, rpPtr)
}
}
if let maxCommitTimeMS = options?.maxCommitTimeMS {
mongoc_transaction_opts_set_max_commit_time_ms(optionsPtr, Int64(maxCommitTimeMS))
}
return try body(optionsPtr)
}
/// An operation corresponding to starting a transaction.
internal struct StartTransactionOperation: Operation {
/// The options to use when starting this transaction.
private let options: TransactionOptions?
internal init(options: TransactionOptions?) {
self.options = options
}
internal func execute(using _: Connection, session: ClientSession?) throws {
guard let session = session else {
throw MongoError.InternalError(message: "No session provided to StartTransactionOperation")
}
var error = bson_error_t()
let success = try session.withMongocSession { sessionPtr in
withMongocTransactionOpts(copying: self.options) { opts in
mongoc_client_session_start_transaction(sessionPtr, opts, &error)
}
}
guard success else {
throw extractMongoError(error: error)
}
}
}
| 33.604396 | 113 | 0.694245 |
fc0df5fc8e0d43f063005d7ac9c00bfdf27fc9a3 | 8,896 | //
// ARViewController+ARSCNView.swift
// ARSample
//
// Created by ji-no on R 4/02/05
//
//
import ARKit
extension ARViewController {
func setUpScene() {
sceneView.delegate = self
sceneView.scene = SCNScene()
sceneView.debugOptions = [SCNDebugOptions.showFeaturePoints]
runSession()
setUpGesture()
setLight()
cursor.isHidden = true
sceneView.scene.rootNode.addChildNode(cursor)
}
func spawn(_ type: ARObjectNode.ObjectType) {
let position = cursor.position
let objectNode = ARObjectNode(type: type, position: position)
self.sceneView.scene.rootNode.addChildNode(objectNode)
self.selectObject(objectNode)
}
func removeObject() {
if let objectNode = selectedObject {
selectObject(nil)
objectNode.removeObject()
}
}
func selectObject(_ objectNode: ARObjectNode?) {
if selectedObject == objectNode {
selectedObject?.select()
} else {
selectedObject?.cancel()
objectNode?.select()
selectedObject = objectNode
}
if let selectedObject = self.selectedObject {
objectNameLabel.isHidden = false
objectNameLabel.text = selectedObject.name
removeButton.isHidden = false
selectButton.isHidden = false
selectButton.setTitle(selectedObject.isSelected() ? "deselect" : "select", for: .normal)
cursor.position = selectedObject.position
cursor.select(size: selectedObject.modelRoot.boundingBoxSize)
} else {
objectNameLabel.isHidden = true
removeButton.isHidden = true
selectButton.isHidden = true
cursor.unselect()
}
}
private func runSession() {
let configuration = ARWorldTrackingConfiguration()
configuration.planeDetection = .horizontal
configuration.isLightEstimationEnabled = true
sceneView.session.run(configuration, options: [.resetTracking, .removeExistingAnchors])
}
private func setUpGesture() {
let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(onTapScene(_:)))
sceneView.addGestureRecognizer(tapGestureRecognizer)
let panGestureRecognizer = UIPanGestureRecognizer(target: self, action: #selector(onSwipeScene(_:)))
sceneView.addGestureRecognizer(panGestureRecognizer)
let rotationGestureRecognizer = UIRotationGestureRecognizer(target: self, action: #selector(onRotationScene(_:)))
sceneView.addGestureRecognizer(rotationGestureRecognizer)
}
private func setLight() {
let light = SCNLight()
light.type = .directional
light.spotInnerAngle = 90
light.spotOuterAngle = 90
light.castsShadow = true
light.zNear = 0
light.zFar = 10
light.shadowMode = .deferred
light.forcesBackFaceCasters = true
light.shadowColor = UIColor.black.withAlphaComponent(0.3)
let lightNode = SCNNode()
lightNode.name = "directionalLight"
lightNode.light = light
lightNode.eulerAngles = SCNVector3Make(Float(-Double.pi / 2), 0, 0)
sceneView.scene.rootNode.addChildNode(lightNode)
}
}
// MARK: - UIGestureRecognizer action
extension ARViewController {
@objc private func onTapScene(_ sender: UITapGestureRecognizer) {
let location = sender.location(in: sceneView)
selectObject(hitObjectNode(location: location))
}
@objc private func onSwipeScene(_ sender: UIPanGestureRecognizer) {
switch sender.state {
case .began:
let location = sender.location(in: sceneView)
if let objectNode = hitObjectNode(location: location) {
selectObject(objectNode)
}
if let position = sceneView.realWorldVector(for: location) {
if let selectedObject = selectedObject {
if selectedObject.isSelected() == false {
selectedObject.select()
}
swipeStartPosition = position
swipeStartObjectPosition = selectedObject.position
}
}
case .changed:
let location = sender.location(in: sceneView)
if let position = sceneView.realWorldVector(for: location) {
translateObject(selectedObject, position: position)
}
default:
break
}
}
@objc private func onRotationScene(_ sender: UIRotationGestureRecognizer) {
if selectedObject?.isSelected() == false {
selectedObject?.select()
}
rotateObject(selectedObject, rotation: Float(sender.rotation))
sender.rotation = 0
}
private func translateObject(_ objectNode: ARObjectNode?, position: SCNVector3) {
guard let objectNode = objectNode else { return }
guard let swipeStartPosition = self.swipeStartPosition else { return }
guard let swipeStartObjectPosition = self.swipeStartObjectPosition else { return }
let newPosition = swipeStartObjectPosition + position - swipeStartPosition
objectNode.position.x = newPosition.x
objectNode.position.z = newPosition.z
cursor.position.x = newPosition.x
cursor.position.z = newPosition.z
}
private func rotateObject(_ objectNode: ARObjectNode?, rotation: Float) {
guard let objectNode = objectNode else { return }
let currentAngles = objectNode.eulerAngles
let newEulerAngles = SCNVector3(currentAngles.x, currentAngles.y - rotation, currentAngles.z)
objectNode.eulerAngles = newEulerAngles
}
private func hitObjectNode(location: CGPoint) -> ARObjectNode? {
let results = sceneView.hitTest(location, options: [SCNHitTestOption.searchMode : SCNHitTestSearchMode.all.rawValue])
return results
.compactMap { $0.node.asObjectNode() }
.first
}
}
// MARK: - ARSCNViewDelegate
extension ARViewController: ARSCNViewDelegate {
func renderer(_ renderer: SCNSceneRenderer, updateAtTime time: TimeInterval) {
guard let frame = sceneView.session.currentFrame else {return}
sceneView.updateLightingEnvironment(for: frame)
if let pointOfView = sceneView.pointOfView {
selectedObject?.update(cameraPosition: pointOfView.position)
}
if selectedObject == nil {
DispatchQueue.main.async { [weak self] in
guard let self = self else { return }
if let worldTransform = self.sceneView.realWorldTransform(for: self.screenCenter) {
if self.selectedObject == nil {
self.cursor.simdTransform = worldTransform
}
}
}
}
}
func session(_ session: ARSession, cameraDidChangeTrackingState camera: ARCamera) {
statusLabel.text = camera.trackingState.description
}
func renderer(_ renderer: SCNSceneRenderer, didAdd node: SCNNode, for anchor: ARAnchor) {
guard let planeAnchor = anchor as? ARPlaneAnchor else { return }
guard let planeGeoemtry = ARSCNPlaneGeometry(device: sceneView.device!) else { fatalError() }
planeAnchor.addPlaneNode(on: node, geometry: planeGeoemtry, contents: UIColor.yellow.withAlphaComponent(0.1))
DispatchQueue.main.async(execute: {
self.statusLabel.text = "a new node has been mapped."
self.cursor.isHidden = false
})
}
func renderer(_ renderer: SCNSceneRenderer, didUpdate node: SCNNode, for anchor: ARAnchor) {
guard let planeAnchor = anchor as? ARPlaneAnchor else { return }
planeAnchor.updatePlaneGeometryNode(on: node)
if let lightEstimate = sceneView.session.currentFrame?.lightEstimate {
if let lightNode = sceneView.scene.rootNode.childNode(withName: "directionalLight", recursively: false) {
lightNode.light?.intensity = lightEstimate.ambientIntensity
lightNode.light?.temperature = lightEstimate.ambientColorTemperature
}
}
DispatchQueue.main.async(execute: {
self.statusLabel.text = "a node has been updated."
})
}
func renderer(_ renderer: SCNSceneRenderer, didRemove node: SCNNode, for anchor: ARAnchor) {
guard let planeAnchor = anchor as? ARPlaneAnchor else { return }
planeAnchor.findPlaneGeometryNode(on: node)?.removeFromParentNode()
DispatchQueue.main.async(execute: {
self.statusLabel.text = "a mapped node has been removed."
})
}
}
| 36.310204 | 125 | 0.637478 |
e513310bc9c23ed1dc2666850d942489cdbde17a | 515 | //
// AgeRanges.swift
// PokerAgent
//
// Created by Alex Constantine on 5/17/18.
// Copyright © 2018 Alex Constantine. All rights reserved.
//
import Foundation
enum AgeRange: String {
case teens = "Teenager"
case twenties = "Twenties"
case thirties = "Thirties"
case fourties = "Fourties"
case fifties = "Fifties"
case sixties = "Sixties"
case seventies = "Seventies"
case eighties = "Eighties"
case nineties = "Nineties"
case unspecified = "Unspecified"
}
| 20.6 | 59 | 0.650485 |
6421adfdea6b37ae7bb27cc9723d2d1ccce5fb29 | 375 | //
// Int+DigitCount.swift
// fujiko
//
// Created by Charlie Cai on 27/3/20.
// Copyright © 2020 tickboxs. All rights reserved.
//
import Foundation
extension Int {
func numberOfDigits() -> Int {
if self < 10 && self >= 0 || self > -10 && self < 0 {
return 1
} else {
return 1 + (self/10).numberOfDigits()
}
}
}
| 18.75 | 61 | 0.530667 |
efb47af94f0b0e4951c676c64b4ebd92e2d986fc | 7,725 | //
// LetterAvatarKit.swift
// LetterAvatarKit
//
// Copyright 2017 Victor Peschenkov
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// o this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import UIKit
/// Uses for making letter-based avatar images.
@objc(LKLetterAvatarBuilder)
open class LetterAvatarBuilder: NSObject {
/// Makes a letter-based avatar image by using a given configuration.
///
/// - Parameters:
/// - configuration: A configuration that is used to draw a
/// letter-based avatar image.
///
/// - Returns: Returns whether an instance of UIImage or nil.
@objc(makeAvatarWithConfiguration:)
open func makeAvatar(with configuration: LetterAvatarBuilderConfiguration) -> UIImage? {
let colors = configuration.backgroundColors
guard let username = configuration.username else {
return drawAvatar(
with: configuration,
letters: NSLocalizedString("NA", comment: ""),
backgroundColor: colors[0].cgColor
)
}
let usernameInfo = UsernameInfo(
username: username,
singleLetter: configuration.useSingleLetter
)
var colorIndex = 0
if colors.count > 1 {
colorIndex = usernameInfo.ASCIIValue
colorIndex *= 3557 // Prime number
colorIndex %= colors.count - 1
}
let backgroundColor = colors[colorIndex].cgColor
return drawAvatar(
with: configuration,
letters: usernameInfo.letters,
backgroundColor: backgroundColor
)
}
private func drawAvatar(
with configuration: LetterAvatarBuilderConfiguration,
letters: String,
backgroundColor: CGColor
) -> UIImage? {
let rect = CGRect(x: 0.0, y: 0.0, width: configuration.size.width, height: configuration.size.height)
UIGraphicsBeginImageContextWithOptions(rect.size, configuration.isOpaque, UIScreen.main.scale)
if let context = UIGraphicsGetCurrentContext() {
let borderWidth = configuration.borderWidth
let borderColor = configuration.borderColor.cgColor
let strokeRect = rect.insetBy(dx: borderWidth * 0.5, dy: borderWidth * 0.5)
context.setFillColor(backgroundColor)
context.setStrokeColor(borderColor)
context.setLineWidth(borderWidth)
if configuration.circle {
context.fillEllipse(in: rect)
context.strokeEllipse(in: strokeRect)
} else {
context.fill(rect)
context.stroke(strokeRect)
}
var attributes = configuration.lettersFontAttributes
if attributes == nil {
attributes = [
.paragraphStyle: NSParagraphStyle.default.mutableCopy(),
.font: makeFitFont(withFont: configuration.lettersFont, forSize: rect.size),
.foregroundColor: configuration.lettersColor
]
}
let lettersSize = letters.size(withAttributes: attributes)
let lettersRect = CGRect(
x: (rect.size.width - lettersSize.width) / 2.0,
y: (rect.size.height - lettersSize.height) / 2.0,
width: lettersSize.width,
height: lettersSize.height
)
letters.draw(in: lettersRect, withAttributes: attributes)
let avatarImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return avatarImage
}
return nil
}
private func makeFitFont(withFont font: UIFont?, forSize size: CGSize) -> UIFont {
guard let font = font else {
return UIFont.systemFont(ofSize: min(size.height, size.width) / 2.0)
}
let fitFont = font.withSize(min(size.height, size.width) / 2.0)
return fitFont.pointSize < font.pointSize ? fitFont : font
}
}
private class UsernameInfo {
public var letters: String {
return userInfo.letters
}
public var ASCIIValue: Int {
return userInfo.value
}
private let username: String
private let useSingleLetter: Bool
private typealias InfoContainer = (letters: String, value: Int)
private lazy var userInfo: InfoContainer = {
var letters = String()
var lettersASCIIValue = 0
// Obtains an array of words by using a given username
let components = username.components(separatedBy: " ")
// If there are whether two words or more
if components.count > 1 {
if !useSingleLetter {
for component in components.prefix(3) {
if let letter = component.first {
letters.append(letter)
lettersASCIIValue += letter.ASCIIValue
}
}
} else {
if let firstComponent = components.first {
// Process the firs name letter
if let letter = firstComponent.first {
letters.append(letter)
lettersASCIIValue += letter.ASCIIValue
}
}
}
} else {
// If given just one word
if let component = components.first {
// Process the firs name letter
if let letter = component.first {
letters.append(letter)
lettersASCIIValue += letter.ASCIIValue
// If single Letter is passed as false but the string is a single char,
// this line fails due to out of bounds exception.
// https://github.com/vpeschenkov/LetterAvatarKit/issues/11
if !useSingleLetter && component.count >= 2 {
// Process the second name letter
let startIndex = component.index(after: component.startIndex)
let endIndex = component.index(component.startIndex, offsetBy: 2)
let substring = component[startIndex..<endIndex].capitalized
if let letter = substring.first {
letters.append(letter)
lettersASCIIValue += letter.ASCIIValue
}
}
}
}
}
return (letters: letters, value: lettersASCIIValue)
}()
init(username: String, singleLetter: Bool) {
self.username = username
self.useSingleLetter = singleLetter
}
}
| 40.873016 | 109 | 0.596505 |
90ff88c6b7825162b1edc4f2430a6b7cd068013c | 5,238 | //
// +DBArray.swift
// Flatland
//
// Created by Stuart Rankin on 2/9/21.
// Copyright © 2021 Stuart Rankin. All rights reserved.
//
import Foundation
import AppKit
extension Settings
{
// MARK: - Array functions.
public static func GetTable<T: RawRepresentable>(_ Setting: SettingKeys, _ ElementType: T.Type) -> [T]
{
if !TypeIsValid(Setting, Type: ElementType)
{
Debug.FatalError("\(Setting) is not valid for GetTable.")
}
switch Setting
{
case .DB_Cities:
break
case .DB_UserCities:
break
case .DB_BuiltInPOIs:
break
case .DB_UserPOIs:
break
case .DB_Homes:
break
case .DB_WorldHeritageSites:
break
default:
Debug.FatalError("Encountered setting \(Setting) when not expected in GetTable in \(#function).")
}
return [T]()
}
public static func SetTable<T: RawRepresentable>(_ Setting: SettingKeys, _ ElementType: T.Type, _ Value: T)
{
if !TypeIsValid(Setting, Type: ElementType)
{
Debug.FatalError("\(Setting) is not valid for SetTable.")
}
switch Setting
{
case .DB_Cities:
break
case .DB_UserCities:
break
case .DB_BuiltInPOIs:
break
case .DB_UserPOIs:
break
case .DB_Homes:
break
case .DB_WorldHeritageSites:
break
default:
Debug.FatalError("Encountered setting \(Setting) when not expected in \(#function).")
}
NotifySubscribers(Setting: Setting, OldValue: nil, NewValue: nil)
}
public static func DeleteRow<T: RawRepresentable>(_ Setting: SettingKeys, _ ElementType: T.Type, _ RowPK: Int)
{
if !TypeIsValid(Setting, Type: ElementType)
{
Debug.FatalError("\(Setting) is not valid for DeleteRow.")
}
switch Setting
{
case .DB_Cities:
Debug.Print("Deleting rows in built-in city list not supported.")
return
case .DB_UserCities:
break
case .DB_BuiltInPOIs:
Debug.Print("Deleting rows in built-in POI list not supported.")
return
case .DB_UserPOIs:
break
case .DB_Homes:
break
case .DB_WorldHeritageSites:
Debug.Print("Deleting rows in built-in World Heritage Site list not supported.")
return
default:
Debug.FatalError("Encountered setting \(Setting) when not expected in \(#function).")
}
}
public static func AddRow<T: RawRepresentable>(_ Setting: SettingKeys, _ ElementType: T.Type, _ Value: T)
{
if !TypeIsValid(Setting, Type: ElementType)
{
Debug.FatalError("\(Setting) is not valid for AddRow.")
}
switch Setting
{
case .DB_Cities:
Debug.Print("Adding rows in built-in city list not supported.")
return
case .DB_UserCities:
break
case .DB_BuiltInPOIs:
Debug.Print("Adding rows in built-in POI list not supported.")
return
case .DB_UserPOIs:
break
case .DB_Homes:
break
case .DB_WorldHeritageSites:
Debug.Print("Adding rows in built-in World Heritage Site list not supported.")
return
default:
Debug.FatalError("Encountered setting \(Setting) when not expected in \(#function).")
}
}
public static func AddRows<T: RawRepresentable>(_ Setting: SettingKeys, _ ElementType: T.Type, _ Values: [T])
{
if !TypeIsValid(Setting, Type: ElementType)
{
Debug.FatalError("\(Setting) is not valid for AddRows.")
}
switch Setting
{
case .DB_Cities:
Debug.Print("Adding rows in built-in city list not supported.")
return
case .DB_UserCities:
break
case .DB_BuiltInPOIs:
Debug.Print("Adding rows in built-in POI list not supported.")
return
case .DB_UserPOIs:
break
case .DB_Homes:
break
case .DB_WorldHeritageSites:
Debug.Print("Adding rows in built-in World Heritage Site list not supported.")
return
default:
Debug.FatalError("Encountered setting \(Setting) when not expected in \(#function).")
}
}
}
| 30.811765 | 114 | 0.494845 |
2106b1af5a1c13e259000038a61d967a60dccb75 | 4,789 | @_exported import Foundation
@available(iOS 8.0, *)
@available(swift, obsoleted: 4.2, renamed: "UIBlurEffect.Style")
typealias UIBlurEffectStyle = UIBlurEffect.Style
extension UIBlurEffect {
@available(iOS 8.0, *)
enum Style : Int {
init?(rawValue: Int)
var rawValue: Int { get }
typealias RawValue = Int
case extraLight
@available(swift, obsoleted: 3, renamed: "extraLight")
static var ExtraLight: UIBlurEffect.Style { get }
case light
@available(swift, obsoleted: 3, renamed: "light")
static var Light: UIBlurEffect.Style { get }
case dark
@available(swift, obsoleted: 3, renamed: "dark")
static var Dark: UIBlurEffect.Style { get }
@available(iOS, unavailable)
case extraDark
@available(iOS 10.0, *)
case regular
@available(iOS 10.0, *)
@available(swift, obsoleted: 3, renamed: "regular")
static var Regular: UIBlurEffect.Style { get }
@available(iOS 10.0, *)
case prominent
@available(iOS 10.0, *)
@available(swift, obsoleted: 3, renamed: "prominent")
static var Prominent: UIBlurEffect.Style { get }
@available(iOS 13.0, *)
case systemUltraThinMaterial
@available(iOS 13.0, *)
@available(swift, obsoleted: 3, renamed: "systemUltraThinMaterial")
static var SystemUltraThinMaterial: UIBlurEffect.Style { get }
@available(iOS 13.0, *)
case systemThinMaterial
@available(iOS 13.0, *)
@available(swift, obsoleted: 3, renamed: "systemThinMaterial")
static var SystemThinMaterial: UIBlurEffect.Style { get }
@available(iOS 13.0, *)
case systemMaterial
@available(iOS 13.0, *)
@available(swift, obsoleted: 3, renamed: "systemMaterial")
static var SystemMaterial: UIBlurEffect.Style { get }
@available(iOS 13.0, *)
case systemThickMaterial
@available(iOS 13.0, *)
@available(swift, obsoleted: 3, renamed: "systemThickMaterial")
static var SystemThickMaterial: UIBlurEffect.Style { get }
@available(iOS 13.0, *)
case systemChromeMaterial
@available(iOS 13.0, *)
@available(swift, obsoleted: 3, renamed: "systemChromeMaterial")
static var SystemChromeMaterial: UIBlurEffect.Style { get }
@available(iOS 13.0, *)
case systemUltraThinMaterialLight
@available(iOS 13.0, *)
@available(swift, obsoleted: 3, renamed: "systemUltraThinMaterialLight")
static var SystemUltraThinMaterialLight: UIBlurEffect.Style { get }
@available(iOS 13.0, *)
case systemThinMaterialLight
@available(iOS 13.0, *)
@available(swift, obsoleted: 3, renamed: "systemThinMaterialLight")
static var SystemThinMaterialLight: UIBlurEffect.Style { get }
@available(iOS 13.0, *)
case systemMaterialLight
@available(iOS 13.0, *)
@available(swift, obsoleted: 3, renamed: "systemMaterialLight")
static var SystemMaterialLight: UIBlurEffect.Style { get }
@available(iOS 13.0, *)
case systemThickMaterialLight
@available(iOS 13.0, *)
@available(swift, obsoleted: 3, renamed: "systemThickMaterialLight")
static var SystemThickMaterialLight: UIBlurEffect.Style { get }
@available(iOS 13.0, *)
case systemChromeMaterialLight
@available(iOS 13.0, *)
@available(swift, obsoleted: 3, renamed: "systemChromeMaterialLight")
static var SystemChromeMaterialLight: UIBlurEffect.Style { get }
@available(iOS 13.0, *)
case systemUltraThinMaterialDark
@available(iOS 13.0, *)
@available(swift, obsoleted: 3, renamed: "systemUltraThinMaterialDark")
static var SystemUltraThinMaterialDark: UIBlurEffect.Style { get }
@available(iOS 13.0, *)
case systemThinMaterialDark
@available(iOS 13.0, *)
@available(swift, obsoleted: 3, renamed: "systemThinMaterialDark")
static var SystemThinMaterialDark: UIBlurEffect.Style { get }
@available(iOS 13.0, *)
case systemMaterialDark
@available(iOS 13.0, *)
@available(swift, obsoleted: 3, renamed: "systemMaterialDark")
static var SystemMaterialDark: UIBlurEffect.Style { get }
@available(iOS 13.0, *)
case systemThickMaterialDark
@available(iOS 13.0, *)
@available(swift, obsoleted: 3, renamed: "systemThickMaterialDark")
static var SystemThickMaterialDark: UIBlurEffect.Style { get }
@available(iOS 13.0, *)
case systemChromeMaterialDark
@available(iOS 13.0, *)
@available(swift, obsoleted: 3, renamed: "systemChromeMaterialDark")
static var SystemChromeMaterialDark: UIBlurEffect.Style { get }
}
}
@available(iOS 8.0, *)
class UIBlurEffect : UIVisualEffect {
/*not inherited*/ init(style: UIBlurEffect.Style)
@available(*, unavailable, renamed: "init(style:)", message: "Not available in Swift")
class func effectWithStyle(_ style: UIBlurEffect.Style) -> UIBlurEffect
init()
init?(coder: NSCoder)
}
| 40.584746 | 88 | 0.702861 |
899352c82b8e4a7e06d53b0ba2499b5c5d5adbdf | 243 | //
// Comparable.swift
//
//
// Created by Christopher Weems on 10/19/21.
//
extension Comparable {
public func bounded(within boundingRange: PartialRangeThrough<Self>) -> Self {
min(self, boundingRange.upperBound)
}
}
| 17.357143 | 82 | 0.658436 |
2981ca976cddcffa1c23713050cd9136d9c41dba | 1,178 | //
// TrelloFunction.swift
// TrelloNavigation
//
// Created by DianQK on 15/11/12.
// Copyright © 2015年 Qing. All rights reserved.
//
import UIKit
/// Taste Function Programming
// TODO: Combine CGPoint
typealias TransformPoint = (CGPoint) -> CGPoint
func add(x: CGFloat) -> TransformPoint {
return { point in
return CGPoint(x: point.x + x, y: point.y)
}
}
func add(y: CGFloat) -> TransformPoint {
return { point in
return CGPoint(x: point.x, y: point.y + y)
}
}
func add(x: CGFloat, y: CGFloat) -> TransformPoint {
return { point in
return add(y: y)( add(x: x)(point) )
}
}
extension UIBezierPath {
func addSquare(center: CGPoint, width: CGFloat) {
self.move(to: add(x: center.x - width / 2.0, y: center.y - width / 2.0)(center))
self.addLine(to: add(x: center.x + width / 2.0, y: center.y - width / 2.0)(center))
self.addLine(to: add(x: center.x + width / 2.0, y: center.y + width / 2.0)(center))
self.addLine(to: add(x: center.x - width / 2.0, y: center.y + width / 2.0)(center))
self.addLine(to: add(x: center.x - width / 2.0, y: center.y - width / 2.0)(center))
}
}
| 28.047619 | 91 | 0.602716 |
5082c0165e24562835100c10dace2d90c60ee977 | 1,682 | //
// DXYN.swift
// Chip8Tests
//
// Created by Lukáš Hromadník on 20/04/2020.
// Copyright © 2020 Lukáš Hromadník. All rights reserved.
//
import XCTest
@testable import Chip8
final class OpCodeDXYNTests: Chip8TestCase {
func testRandom() {
chip8.clearDisplay()
chip8.vI = 0
let (x, y) = generateRandomRegisters()
let coordX: Int = .random(in: 0..<kDisplayWidth)
let coordY: Int = .random(in: 0..<kDisplayHeight)
chip8.v[x] = UInt8(coordX)
chip8.v[y] = UInt8(coordY)
let height: Int = .random(in: 0...0xF)
var sprite = [UInt8](repeating: 0, count: height)
for i in 0..<height { sprite[i] = .random() }
for i in 0..<sprite.count {
chip8.memory[Int(chip8.vI) + i] = sprite[i]
}
chip8.opcode = 0xD000 | UInt16(x) << 8 | UInt16(y) << 4 | UInt16(height)
XCTAssertNoThrow(try chip8.decodeOpcode())
for j in 0..<kDisplayHeight {
for i in 0..<kDisplayWidth {
let index = j * kDisplayWidth + i
if (coordX..<coordX + kSpriteLength).contains(i) && (coordY..<coordY + height).contains(j) {
let row = sprite[j - coordY]
let pixelValue = row >> (kSpriteLength - 1 - (i - coordX))
let pixel: UInt8 = pixelValue & 1
XCTAssertEqual(chip8.display[index], pixel)
} else {
if chip8.display[index] != 0 {
print(coordX, coordY, i, j, index)
}
XCTAssertEqual(chip8.display[index], 0)
}
}
}
}
}
| 32.980392 | 108 | 0.519025 |
f9bce409f3e8bc4a49c53ead645361db05ff82b7 | 3,063 | import ArgumentParser
import Foundation
import MockingbirdAutomation
import PathKit
extension Build {
struct BuildCli: ParsableCommand {
static var configuration = CommandConfiguration(
commandName: "cli",
abstract: "Build the command line interface.")
@Option(name: .customLong("sign"), help: "Identity used to sign the built binary.")
var signingIdentity: String?
@Option(help: "File path containing the designated requirement for codesigning.")
var requirements: String =
"./Sources/MockingbirdAutomationCli/Resources/CodesigningRequirements/mockingbird.txt"
@OptionGroup()
var globalOptions: Options
func getVersionString() throws -> String {
return try PlistBuddy.printValue(key: "CFBundleShortVersionString",
plist: Path("./Sources/MockingbirdCli/Info.plist"))
}
func fixupRpaths(binary: Path) throws {
let version = try getVersionString()
// Get rid of toolchain-dependent rpaths which aren't guaranteed to have a compatible version
// of the internal SwiftSyntax parser lib.
let developerDirectory = try XcodeSelect.printPath()
let swiftToolchainPath = developerDirectory
+ "Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx"
try InstallNameTool.deleteRpath(swiftToolchainPath.absolute().string, binary: binary)
// Swift 5.5 is only present in Xcode 13.2+
let swift5_5ToolchainPath = developerDirectory
+ "Toolchains/XcodeDefault.xctoolchain/usr/lib/swift-5.5/macosx"
try? InstallNameTool.deleteRpath(swift5_5ToolchainPath.absolute().string, binary: binary)
// Add new rpaths in descending order of precedence.
try InstallNameTool.addRpath("/usr/lib/mockingbird/\(version)", binary: binary)
// Support environments with restricted write permissions to system resources.
try InstallNameTool.addRpath("/var/tmp/lib/mockingbird/\(version)", binary: binary)
try InstallNameTool.addRpath("/tmp/lib/mockingbird/\(version)", binary: binary)
}
func run() throws {
let packagePath = Path("./Package.swift")
let cliPath = try SwiftPackage.build(target: .product(name: "mockingbird"),
configuration: .release,
packageConfiguration: .executables,
package: packagePath)
try fixupRpaths(binary: cliPath)
if let identity = signingIdentity {
try Codesign.sign(binary: cliPath, identity: identity)
try Codesign.verify(binary: cliPath, requirements: Path(requirements))
}
if let location = globalOptions.archiveLocation {
let libRoot = Path("./Sources/MockingbirdCli/Resources/Libraries")
let libPaths = libRoot.glob("*.dylib") + [libRoot + "LICENSE.txt"]
try archive(artifacts: [("", cliPath)] + libPaths.map({ ("Libraries", $0) }),
destination: Path(location))
}
}
}
}
| 45.044118 | 99 | 0.662096 |
fe83c2ac964f000ba50c6561e86770b63a8a6fcc | 512 | //
// FormatterExtensions.swift
// GDAXSwift
//
// Created by Anthony on 6/4/17.
// Copyright © 2017 Anthony Puppo. All rights reserved.
//
internal extension Formatter {
internal static let iso8601: DateFormatter = {
let formatter = DateFormatter()
formatter.calendar = Calendar(identifier: .iso8601)
formatter.locale = Locale(identifier: "en_US_POSIX")
formatter.timeZone = TimeZone(secondsFromGMT: 0)
formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSXXXXX"
return formatter
}()
}
| 22.26087 | 57 | 0.714844 |
5b4884379315c117e4eeaea4d3d9bb1fcd531f78 | 1,209 | //
// TimePickerMonthButton.swift
// TimePicker
//
// Created by DeliveLee on 2017/4/20.
// Copyright © 2017年 TimePicker. All rights reserved.
//
import UIKit
class TimePickerMonthButton: UIButton {
var bottomBorder: CALayer = CALayer()
var isActive: Bool = false {
didSet {
if isActive {
self.bottomBorder.backgroundColor = UIColor(rgba:"#FFC816").cgColor
self.setTitleColor(UIColor.black, for: .normal)
}else{
self.bottomBorder.backgroundColor = UIColor.gray.cgColor
self.setTitleColor(UIColor.gray, for: .normal)
}
self.layoutSubviews()
}
}
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
bottomBorder.frame = CGRect(x: 0, y: self.frame.height-2, width: self.frame.width, height: 2)
self.layer.addSublayer(bottomBorder)
}
/*
// Only override draw() if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
override func draw(_ rect: CGRect) {
// Drawing code
}
*/
}
| 24.673469 | 101 | 0.592225 |
eda9e98023ef840481a1c608f63b0fa7040d4e43 | 1,369 | //
// AppDelegate.swift
// PodcastPlayer
//
// Created by Paul Wood on 7/13/19.
// Copyright © 2019 Paul Wood. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
return true
}
// MARK: UISceneSession Lifecycle
func application(_ application: UIApplication, configurationForConnecting connectingSceneSession: UISceneSession, options: UIScene.ConnectionOptions) -> UISceneConfiguration {
// Called when a new scene session is being created.
// Use this method to select a configuration to create the new scene with.
return UISceneConfiguration(name: "Default Configuration", sessionRole: connectingSceneSession.role)
}
func application(_ application: UIApplication, didDiscardSceneSessions sceneSessions: Set<UISceneSession>) {
// Called when the user discards a scene session.
// If any sessions were discarded while the application was not running, this will be called shortly after application:didFinishLaunchingWithOptions.
// Use this method to release any resources that were specific to the discarded scenes, as they will not return.
}
}
| 36.026316 | 177 | 0.772096 |
09104c86d3ff8c61a1d31d6868de1edd156c834e | 578 | //
// ConsoleConfiguration.swift
// LoggerKit
//
// Created by Werck, Ayrton on 18-07-05.
// Copyright (c) 2018 Nuglif. All rights reserved.
//
public struct ConsoleConfiguration: LoggerConfigurationProtocol {
public let formatter: LoggerFormatterProtocol
public let shouldShowLogDetails: Bool
public let filter: FilterProtocol
public init(formatter: LoggerFormatterProtocol, shouldShowLogDetails: Bool, filter: FilterProtocol) {
self.formatter = formatter
self.shouldShowLogDetails = shouldShowLogDetails
self.filter = filter
}
}
| 28.9 | 105 | 0.742215 |
bb4dc22217f62c6f6b99e677d777aefd262734af | 1,232 | //
// SwiftUITVOsTests.swift
// SwiftUITVOsTests
//
// Created by Jose Harold on 29/12/2021.
//
import XCTest
@testable import SwiftUITVOs
class SwiftUITVOsTests: XCTestCase {
override func setUpWithError() throws {
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDownWithError() throws {
// Put teardown code here. This method is called after the invocation of each test method in the class.
}
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.
// Any test you write for XCTest can be annotated as throws and async.
// Mark your test throws to produce an unexpected failure when your test encounters an uncaught error.
// Mark your test async to allow awaiting for asynchronous code to complete. Check the results with assertions afterwards.
}
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.
}
}
}
| 33.297297 | 130 | 0.686688 |
61205eff9497ac997d33e197aef0b875c93b2621 | 1,138 | // Copyright SIX DAY LLC. All rights reserved.
import UIKit
struct NewTokenViewModel {
var title: String {
return R.string.localizable.tokensNewtokenNavigationTitle()
}
var ERC875TokenBalance: [String] = []
var ERC875TokenBalanceAmount: Int {
var balance = 0
if !ERC875TokenBalance.isEmpty {
for _ in 0...ERC875TokenBalance.count - 1 {
balance += 1
}
}
return balance
}
var backgroundColor: UIColor {
return Colors.appBackground
}
var choiceLabelColor: UIColor {
return Colors.appGrayLabel
}
var choiceLabelFont: UIFont {
return Fonts.regular(size: 10)
}
var addressLabel: String {
return R.string.localizable.contractAddress()
}
var symbolLabel: String {
return R.string.localizable.symbol()
}
var decimalsLabel: String {
return R.string.localizable.decimals()
}
var balanceLabel: String {
return R.string.localizable.balance()
}
var nameLabel: String {
return R.string.localizable.name()
}
}
| 21.074074 | 67 | 0.608963 |
9b76249d851a8190d5f6d354c677e6c96e58b9fb | 270 | //
// DiscoveryCollectionViewCell.swift
// Stylist
//
// Created by Oniel Rosario on 4/10/19.
// Copyright © 2019 Ashli Rankin. All rights reserved.
//
import UIKit
class DiscoveryCollectionViewCell: UICollectionViewCell {
@IBOutlet weak var label: UILabel!
}
| 19.285714 | 57 | 0.733333 |
d7cfdc803909563b68bfc818d9e9fb3ef95d9818 | 8,211 | //
// Created by Andreas Bauer on 23.01.21.
//
enum RelationshipType: Hashable, CustomStringConvertible, CustomDebugStringConvertible {
/// All relationships from the destination are inherited (including the self relationship).
/// This requires that the `RelationshipSourceCandidate` contains resolvers
/// for all path parameters of the relationship destination.
case inheritance
/// A reference describes a special case of Relationship where properties
/// of the returned data is REPLACED by the relationship (e.g. a link in the REST exporter).
/// This type requires that the `RelationshipSourceCandidate` contains resolvers
/// for all path parameters of the relationship destination.
case reference(name: String)
/// A link is any kind of Relationship. It doesn't enforce any path parameters to be resolved
/// (although it can be resolved if wanted).
case link(name: String)
var description: String {
switch self {
case .inheritance:
return "inheritance"
case .reference:
return "reference"
case .link:
return "link"
}
}
var debugDescription: String {
switch self {
case .inheritance:
return "inheritance"
case let .reference(name):
return #"reference(name: "\#(name)")"#
case let .link(name):
return #"link(name: "\#(name)")"#
}
}
var checkResolvers: Bool {
if case .link = self {
return false
}
return true
}
func hash(into hasher: inout Hasher) {
description.hash(into: &hasher)
}
static func == (lhs: RelationshipType, rhs: RelationshipType) -> Bool {
switch (lhs, rhs) {
case (.inheritance, .inheritance),
(.reference, .reference),
(.link, .link):
return true
default:
return false
}
}
}
/// Defines a relationship source candidate, either a resolved `RelationshipSourceCandidate` or unresolved `PartialRelationshipSourceCandidate`
protocol SomeRelationshipSourceCandidate: CustomDebugStringConvertible {
var type: RelationshipType { get }
var destinationType: Any.Type { get }
var reference: EndpointReference { get }
var resolvers: [AnyPathParameterResolver] { get }
/// Returns a resolved version of the candidate representation
func ensureResolved(using builder: RelationshipBuilder) -> RelationshipSourceCandidate
}
/// Represents a candidate for a `EndpointRelationship` create using type information
/// (either completely automatically or by type hints from the user)
struct RelationshipSourceCandidate: SomeRelationshipSourceCandidate {
var debugDescription: String {
"RelationshipCandidate(\(type.debugDescription), targeting: \(destinationType), resolvers: \(resolvers.count))"
}
/// Defines the type of `RelationshipSourceCandidate`. See `RelationshipType`.
/// For `.reference` type this implicitly defines the name of the relationship.
let type: RelationshipType
/// Defines the type of the destination in the `TypeIndex`
let destinationType: Any.Type
/// Defines the reference to the source
let reference: EndpointReference
let resolvers: [AnyPathParameterResolver]
/// Initializes a `RelationshipSourceCandidate` with type of inheritance.
init(destinationType: Any.Type, reference: EndpointReference, resolvers: [AnyPathParameterResolver]) {
self.type = .inheritance
self.destinationType = destinationType
self.reference = reference
self.resolvers = resolvers
}
fileprivate init(from partialCandidate: PartialRelationshipSourceCandidate,
reference: EndpointReference,
using builder: RelationshipBuilder) {
self.type = partialCandidate.type
self.destinationType = partialCandidate.destinationType
self.reference = reference
var parameterResolvers: [AnyPathParameterResolver]
if case .inheritance = type {
parameterResolvers = reference.absolutePath.listPathParameters().resolvers()
} else {
// We take all resolver used for inheritance into account in order for this to work
// the `TypeIndex.resolve` steps MUST parse inheritance candidates FIRST.
parameterResolvers = builder.selfRelationshipResolvers(for: reference)
}
// inserting manually defined resolvers BEFORE the "automatically" derived path parameter resolvers
// to avoid conflicting resolvers (e.g. path parameter resolving the same parameter as property resolver)
parameterResolvers.insert(contentsOf: partialCandidate.resolvers, at: 0)
self.resolvers = parameterResolvers
}
func ensureResolved(using builder: RelationshipBuilder) -> RelationshipSourceCandidate {
self
}
}
/// A `RelationshipSourceCandidate` but without the scope of the `Endpoint`
/// meaning still missing the `EndpointReference` and missing any `PathParameterResolver` in the `resolvers`.
public struct PartialRelationshipSourceCandidate: SomeRelationshipSourceCandidate {
public var debugDescription: String {
"PartialRelationshipSourceCandidate(\(type.debugDescription), targeting: \(destinationType), resolvers: \(resolvers.count))"
}
/// Defines the type of `PartialRelationshipSourceCandidate`. See `RelationshipType`.
/// For `.reference` type this implicitly defines the name of the relationship.
let type: RelationshipType
/// Defines the type of the destination in the `TypeIndex`
let destinationType: Any.Type
let resolvers: [AnyPathParameterResolver]
/// Defines the reference to the source
var reference: EndpointReference {
guard let reference = storedReference else {
fatalError("Tried accessing reference of PartialRelationshipSourceCandidate which wasn't linked to an Endpoint yet!")
}
return reference
}
var storedReference: EndpointReference?
/// Initializes a `RelationshipSourceCandidate` with type of inheritance.
init(destinationType: Any.Type, resolvers: [AnyPathParameterResolver]) {
self.type = .inheritance
self.destinationType = destinationType
self.resolvers = resolvers
}
/// Initializes a `RelationshipSourceCandidate` with type of reference.
init(reference name: String, destinationType: Any.Type, resolvers: [AnyPathParameterResolver]) {
self.type = .reference(name: name)
self.destinationType = destinationType
self.resolvers = resolvers
}
/// Initializes a `RelationshipSourceCandidate` with type of reference.
init(link name: String, destinationType: Any.Type, resolvers: [AnyPathParameterResolver] = []) {
self.type = .link(name: name)
self.destinationType = destinationType
self.resolvers = resolvers
}
mutating func link(to endpoint: _AnyRelationshipEndpoint) {
storedReference = endpoint.reference
}
func ensureResolved(using builder: RelationshipBuilder) -> RelationshipSourceCandidate {
RelationshipSourceCandidate(from: self, reference: reference, using: builder)
}
}
extension Array where Element == PartialRelationshipSourceCandidate {
func linked(to endpoint: _AnyRelationshipEndpoint) -> [PartialRelationshipSourceCandidate] {
map {
var candidate = $0
candidate.link(to: endpoint)
return candidate
}
}
}
extension Array where Element == RelationshipSourceCandidate {
/// Index the `RelationshipSourceCandidate` array by the `EndpointReference` stored in `reference`.
func referenceIndexed() -> CollectedRelationshipCandidates {
var candidates: CollectedRelationshipCandidates = [:]
for sourceCandidate in self {
var collectedCandidates = candidates[sourceCandidate.reference, default: []]
collectedCandidates.append(sourceCandidate)
candidates[sourceCandidate.reference] = collectedCandidates
}
return candidates
}
}
| 39.859223 | 143 | 0.694069 |
0130d07fdc369827adbfaf4fbe7c285e77ef3167 | 9,127 | //
// SwiftRandom.swift
//
// Created by Furkan Yilmaz on 7/10/15.
// Copyright (c) 2015 Furkan Yilmaz. All rights reserved.
//
import Foundation
// each type has its own random
public extension Bool {
/// SwiftRandom extension
static func random() -> Bool {
return Int.random() % 2 == 0
}
}
public extension Int {
/// SwiftRandom extension
static func random(_ lower: Int = 0, _ upper: Int = 100) -> Int {
return Int.random(in: lower...upper)
}
}
public extension Int32 {
/// SwiftRandom extension
///
/// - note: Using `Int` as parameter type as we usually just want to write `Int32.random(13, 37)` and not `Int32.random(Int32(13), Int32(37))`
static func random(_ lower: Int = 0, _ upper: Int = 100) -> Int32 {
return Int32.random(in: Int32(lower)...Int32(upper))
}
}
public extension String {
/// SwiftRandom extension
static func random(ofLength length: Int) -> String {
return random(minimumLength: length, maximumLength: length)
}
/// SwiftRandom extension
static func random(minimumLength min: Int, maximumLength max: Int) -> String {
return random(
withCharactersInString: "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789",
minimumLength: min,
maximumLength: max
)
}
/// SwiftRandom extension
static func random(withCharactersInString string: String, ofLength length: Int) -> String {
return random(
withCharactersInString: string,
minimumLength: length,
maximumLength: length
)
}
/// SwiftRandom extension
static func random(withCharactersInString string: String, minimumLength min: Int, maximumLength max: Int) -> String {
guard min > 0 && max >= min else {
return ""
}
let length: Int = (min < max) ? .random(in: min...max) : max
var randomString = ""
(1...length).forEach { _ in
let randomIndex: Int = .random(in: 0..<string.count)
let c = string.index(string.startIndex, offsetBy: randomIndex)
randomString += String(string[c])
}
return randomString
}
}
public extension Double {
/// SwiftRandom extension
static func random(_ lower: Double = 0, _ upper: Double = 100) -> Double {
return Double.random(in: lower...upper)
}
}
public extension Float {
/// SwiftRandom extension
static func random(_ lower: Float = 0, _ upper: Float = 100) -> Float {
return Float.random(in: lower...upper)
}
}
public extension CGFloat {
/// SwiftRandom extension
static func random(_ lower: CGFloat = 0, _ upper: CGFloat = 1) -> CGFloat {
return CGFloat.random(in: lower...upper)
}
}
public extension URL {
/// SwiftRandom extension
static func random() -> URL {
let urlList = ["http://www.google.com", "http://leagueoflegends.com/", "https://github.com/", "http://stackoverflow.com/", "https://medium.com/", "http://9gag.com/gag/6715049", "http://imgur.com/gallery/s9zoqs9", "https://www.youtube.com/watch?v=uelHwf8o7_U"]
return URL(string: urlList.randomElement()!)!
}
}
public struct Randoms {
//==========================================================================================================
// MARK: - Object randoms
//==========================================================================================================
public static func randomBool() -> Bool {
return Bool.random()
}
public static func randomInt(_ range: Range<Int>) -> Int {
return Int.random(in: range)
}
public static func randomInt(_ lower: Int = 0, _ upper: Int = 100) -> Int {
return Int.random(lower, upper)
}
public static func randomInt32(_ range: Range<Int32>) -> Int32 {
return Int32.random(in: range)
}
public static func randomInt32(_ lower: Int = 0, _ upper: Int = 100) -> Int32 {
return Int32.random(lower, upper)
}
public static func randomString(ofLength length: Int) -> String {
return String.random(ofLength: length)
}
public static func randomString(minimumLength min: Int, maximumLength max: Int) -> String {
return String.random(minimumLength: min, maximumLength: max)
}
public static func randomString(withCharactersInString string: String, ofLength length: Int) -> String {
return String.random(withCharactersInString: string, ofLength: length)
}
public static func randomString(withCharactersInString string: String, minimumLength min: Int, maximumLength max: Int) -> String {
return String.random(withCharactersInString: string, minimumLength: min, maximumLength: max)
}
public static func randomPercentageisOver(_ percentage: Int) -> Bool {
return Int.random() >= percentage
}
public static func randomDouble(_ lower: Double = 0, _ upper: Double = 100) -> Double {
return Double.random(lower, upper)
}
public static func randomFloat(_ lower: Float = 0, _ upper: Float = 100) -> Float {
return Float.random(lower, upper)
}
public static func randomCGFloat(_ lower: CGFloat = 0, _ upper: CGFloat = 1) -> CGFloat {
return CGFloat.random(lower, upper)
}
public static func randomNSURL() -> URL {
return URL.random()
}
//==========================================================================================================
// MARK: - Fake random data generators
//==========================================================================================================
public static func randomFakeName() -> String {
return randomFakeFirstName() + " " + randomFakeLastName()
}
public static func randomFakeFirstName() -> String {
let firstNameList = ["Henry", "William", "Geoffrey", "Jim", "Yvonne", "Jamie", "Leticia", "Priscilla", "Sidney", "Nancy", "Edmund", "Bill", "Megan"]
return firstNameList.randomElement()!
}
public static func randomFakeLastName() -> String {
let lastNameList = ["Pearson", "Adams", "Cole", "Francis", "Andrews", "Casey", "Gross", "Lane", "Thomas", "Patrick", "Strickland", "Nicolas", "Freeman"]
return lastNameList.randomElement()!
}
public static func randomFakeGender() -> String {
return Bool.random() ? "Male" : "Female"
}
public static func randomFakeConversation() -> String {
let convoList = ["You embarrassed me this evening.", "You don't think that was just lemonade in your glass, do you?", "Do you ever think we should just stop doing this?", "Why didn't he come and talk to me himself?", "Promise me you'll look after your mother.", "If you get me his phone, I might reconsider.", "I think the room is bugged.", "No! I'm tired of doing what you say.", "For some reason, I'm attracted to you."]
return convoList.randomElement()!
}
public static func randomFakeTitle() -> String {
let titleList = ["CEO of Google", "CEO of Facebook", "VP of Marketing @Uber", "Business Developer at IBM", "Jungler @ Fanatic", "B2 Pilot @ USAF", "Student at Stanford", "Student at Harvard", "Mayor of Raccoon City", "CTO @ Umbrella Corporation", "Professor at Pallet Town University"]
return titleList.randomElement()!
}
public static func randomFakeTag() -> String {
let tagList = ["meta", "forum", "troll", "meme", "question", "important", "like4like", "f4f"]
return tagList.randomElement()!
}
fileprivate static func randomEnglishHonorific() -> String {
let englishHonorificsList = ["Mr.", "Ms.", "Dr.", "Mrs.", "Mz.", "Mx.", "Prof."]
return englishHonorificsList.randomElement()!
}
public static func randomFakeNameAndEnglishHonorific() -> String {
let englishHonorific = randomEnglishHonorific()
let name = randomFakeName()
return englishHonorific + " " + name
}
public static func randomFakeCity() -> String {
let cityPrefixes = ["North", "East", "West", "South", "New", "Lake", "Port"]
let citySuffixes = ["town", "ton", "land", "ville", "berg", "burgh", "borough", "bury", "view", "port", "mouth", "stad", "furt", "chester", "mouth", "fort", "haven", "side", "shire"]
return cityPrefixes.randomElement()! + citySuffixes.randomElement()!
}
public static func randomCurrency() -> String {
let currencyList = ["USD", "EUR", "GBP", "JPY", "AUD", "CAD", "ZAR", "NZD", "INR", "BRP", "CNY", "EGP", "KRW", "MXN", "SAR", "SGD",]
return currencyList.randomElement()!
}
public enum GravatarStyle: String {
case Standard
case MM
case Identicon
case MonsterID
case Wavatar
case Retro
static let allValues = [Standard, MM, Identicon, MonsterID, Wavatar, Retro]
}
}
| 37.253061 | 430 | 0.587378 |
0aa1a1d8567c51ac7b1495722a87812e0bf07c6f | 7,248 | //
// ImageCache.swift
// ASDKLesson
//
// Created by Pikaurd on 4/16/15.
// Copyright (c) 2015 Shanghai Zuijiao Infomation Technology Inc. All rights reserved.
//
import Foundation
import AsyncDisplayKit
public class ImageCache: NSCache {
static let kDefaultTimeoutLengthInNanoSeconds = 10 * 1_000_000_000 as Int64
private let downloadConcurrentQueue: dispatch_queue_t
private let workingConcurrentQueue: dispatch_queue_t
private let directoryPath: String
private let fileManager: NSFileManager
private var downloadingMap: [NSURL : dispatch_semaphore_t]
required public init(appGroupIdentifier: String? = .None) {
downloadConcurrentQueue = dispatch_queue_create("net.zuijiao.async.DownloadQueue", DISPATCH_QUEUE_CONCURRENT)
workingConcurrentQueue = dispatch_queue_create("net.zuijiao.async.WorkingQueue", DISPATCH_QUEUE_CONCURRENT)
downloadingMap = [ : ]
fileManager = NSFileManager.defaultManager()
directoryPath = ImageCache.generateCacheDirectoryPathByAppGroupIdentifier(fileManager, appGroupIdentifier: appGroupIdentifier)
super.init()
dispatch_barrier_async(workingConcurrentQueue, { () -> Void in
if !self.fileManager.fileExistsAtPath(self.directoryPath) {
var error: NSError?
self.fileManager.createDirectoryAtPath(self.directoryPath
, withIntermediateDirectories: false
, attributes: [:]
, error: &error)
if let error = error {
dispatch_async(dispatch_get_main_queue(), { () -> Void in
debugLog("error: \(error)")
exit(1)
})
}
}
})
}
public func newASNetworkImageNode() -> ASNetworkImageNode {
return ASNetworkImageNode(cache: self, downloader: self)
}
public func clearCache() -> () {
dispatch_barrier_async(workingConcurrentQueue, { () -> Void in
self.removeAllObjects()
self.removePath(self.directoryPath)
})
}
public func clearCache(key: NSURL) -> () {
dispatch_barrier_async(workingConcurrentQueue, { () -> Void in
self.removeObjectForKey(key)
let filePath = self.getFilePath(key)
self.removePath(filePath)
})
}
private func removePath(path: String) -> () {
if self.fileManager.fileExistsAtPath(path) {
var error: NSError?
self.fileManager.removeItemAtPath(path, error: &error)
if let error = error {
dispatch_async(dispatch_get_main_queue(), { () -> Void in
debugLog("error: \(error)")
})
}
}
}
private func persistImage(image: UIImage, withKey key: NSURL) {
dispatch_sync(workingConcurrentQueue, { () -> Void in
self.setObject(image, forKey: key)
let png = UIImagePNGRepresentation(image)
png.writeToFile(self.getFilePath(key), atomically: true)
})
}
public func fetchImage(key: NSURL) -> UIImage? {
let resultImage: UIImage?
if let hittedImage: AnyObject = self.objectForKey(key) { // memory
resultImage = hittedImage as? UIImage
debugLog("Hit")
}
else if imageInDiskCache(key) { // fetch from disk
resultImage = UIImage(contentsOfFile: getFilePath(key))
setObject(resultImage!, forKey: key)
debugLog("Miss")
}
else { // Not hit
resultImage = .None
}
return resultImage
}
private func imageInDiskCache(url: NSURL) -> Bool {
return fileManager.fileExistsAtPath(getFilePath(url))
}
private func getFilePath(url: NSURL) -> String {
return "\(directoryPath)/Cache_\(url.hash).png"
}
private func downloadImage(url: NSURL) -> UIImage? {
if let _ = downloadingMap[url] {
return .None // cancle thread 'cause the url was downloading
}
let sema = dispatch_semaphore_create(0)
downloadingMap.updateValue(sema, forKey: url)
dispatch_async(downloadConcurrentQueue, { () -> Void in
if let data = NSData(contentsOfURL: url) {
if let image = UIImage(data: data) {
self.persistImage(image, withKey: url)
}
}
dispatch_semaphore_signal(sema)
});
let timeout = dispatch_time(DISPATCH_TIME_NOW, ImageCache.kDefaultTimeoutLengthInNanoSeconds)
dispatch_semaphore_wait(sema, timeout);
downloadingMap.removeValueForKey(url)
let resultImage = fetchImage(url)
return resultImage
}
private static func generateCacheDirectoryPathByAppGroupIdentifier(fileManager: NSFileManager, appGroupIdentifier: String?) -> String {
let foldername = "Library/Caches/net.zuijiao.ios.asyncdisplay.ImageCache"
let path: String
if let appGroupIdentifier = appGroupIdentifier {
let url = fileManager.containerURLForSecurityApplicationGroupIdentifier(appGroupIdentifier)
let folderUrl = url!.URLByAppendingPathComponent(foldername).absoluteString!
path = folderUrl.substringFromIndex(advance(folderUrl.startIndex, 7))
}
else {
path = "\(NSHomeDirectory())\(foldername)"
}
return path
}
}
extension ImageCache: ASImageCacheProtocol {
public func fetchCachedImageWithURL(
URL: NSURL!
, callbackQueue: dispatch_queue_t!
, completion: ((CGImage!) -> Void)!
) -> ()
{
dispatch_async(callbackQueue, { () -> Void in
completion(self.fetchImage(URL)?.CGImage)
})
}
}
extension ImageCache: ASImageDownloaderProtocol {
public func downloadImageWithURL(
URL: NSURL!
, callbackQueue: dispatch_queue_t!
, downloadProgressBlock: ((CGFloat) -> Void)!
, completion: ((CGImage!, NSError!) -> Void)!)
-> AnyObject!
{
dispatch_async(workingConcurrentQueue, { () -> Void in
var error: NSError?
let resultImage: UIImage! = self.downloadImage(URL)
if resultImage == .None {
error = NSError(domain: "net.zuijiao.ios.async", code: 0x1, userInfo: ["Reason": "download failed"])
}
dispatch_async(callbackQueue, { () -> Void in
completion(resultImage?.CGImage, error)
})
})
return .None // not implement cancle method
}
public func cancelImageDownloadForIdentifier(downloadIdentifier: AnyObject!) {
debugLog("[Not implement] Do nothing")
}
}
private class DownloadState {
let semaphore: dispatch_semaphore_t
let task: NSURLSessionTask
required init(semaphore: dispatch_semaphore_t, task: NSURLSessionTask) {
self.semaphore = semaphore
self.task = task
}
}
| 32.357143 | 139 | 0.603201 |
cc69952f89d1d02197daccbe7c0f4511659e598a | 16,374 | // Automatically generated by the Fast Binary Encoding compiler, do not modify!
// https://github.com/chronoxor/FastBinaryEncoding
// Source: test.fbe
// Version: 1.3.0.0
import Foundation
import ChronoxorFbe
import ChronoxorProto
// Fast Binary Encoding StructNested field model
public class FieldModelStructNested: FieldModel {
public var _buffer: Buffer
public var _offset: Int
let parent: FieldModelStructOptional
let f1000: FieldModelEnumSimple
let f1001: FieldModelOptionalEnumSimple
let f1002: FieldModelEnumTyped
let f1003: FieldModelOptionalEnumTyped
let f1004: FieldModelFlagsSimple
let f1005: FieldModelOptionalFlagsSimple
let f1006: FieldModelFlagsTyped
let f1007: FieldModelOptionalFlagsTyped
let f1008: FieldModelStructSimple
let f1009: FieldModelOptionalStructSimple
let f1010: FieldModelStructOptional
let f1011: FieldModelOptionalStructOptional
// Field size
public let fbeSize: Int = 4
// Field body size
public let fbeBody: Int
// Set the struct value (end phase)
public required init() {
let buffer = Buffer()
let offset = 0
_buffer = buffer
_offset = offset
parent = FieldModelStructOptional(buffer: buffer, offset: 4 + 4)
f1000 = FieldModelEnumSimple(buffer: buffer, offset: parent.fbeOffset + parent.fbeBody - 4 - 4)
f1001 = FieldModelOptionalEnumSimple(buffer: buffer, offset: f1000.fbeOffset + f1000.fbeSize)
f1002 = FieldModelEnumTyped(buffer: buffer, offset: f1001.fbeOffset + f1001.fbeSize)
f1003 = FieldModelOptionalEnumTyped(buffer: buffer, offset: f1002.fbeOffset + f1002.fbeSize)
f1004 = FieldModelFlagsSimple(buffer: buffer, offset: f1003.fbeOffset + f1003.fbeSize)
f1005 = FieldModelOptionalFlagsSimple(buffer: buffer, offset: f1004.fbeOffset + f1004.fbeSize)
f1006 = FieldModelFlagsTyped(buffer: buffer, offset: f1005.fbeOffset + f1005.fbeSize)
f1007 = FieldModelOptionalFlagsTyped(buffer: buffer, offset: f1006.fbeOffset + f1006.fbeSize)
f1008 = FieldModelStructSimple(buffer: buffer, offset: f1007.fbeOffset + f1007.fbeSize)
f1009 = FieldModelOptionalStructSimple(buffer: buffer, offset: f1008.fbeOffset + f1008.fbeSize)
f1010 = FieldModelStructOptional(buffer: buffer, offset: f1009.fbeOffset + f1009.fbeSize)
f1011 = FieldModelOptionalStructOptional(buffer: buffer, offset: f1010.fbeOffset + f1010.fbeSize)
var fbeBody = (4 + 4)
fbeBody += parent.fbeBody - 4 - 4
fbeBody += f1000.fbeSize
fbeBody += f1001.fbeSize
fbeBody += f1002.fbeSize
fbeBody += f1003.fbeSize
fbeBody += f1004.fbeSize
fbeBody += f1005.fbeSize
fbeBody += f1006.fbeSize
fbeBody += f1007.fbeSize
fbeBody += f1008.fbeSize
fbeBody += f1009.fbeSize
fbeBody += f1010.fbeSize
fbeBody += f1011.fbeSize
self.fbeBody = fbeBody
}
//
public required init(buffer: Buffer = Buffer(), offset: Int = 0) {
_buffer = buffer
_offset = offset
parent = FieldModelStructOptional(buffer: buffer, offset: 4 + 4)
f1000 = FieldModelEnumSimple(buffer: buffer, offset: parent.fbeOffset + parent.fbeBody - 4 - 4)
f1001 = FieldModelOptionalEnumSimple(buffer: buffer, offset: f1000.fbeOffset + f1000.fbeSize)
f1002 = FieldModelEnumTyped(buffer: buffer, offset: f1001.fbeOffset + f1001.fbeSize)
f1003 = FieldModelOptionalEnumTyped(buffer: buffer, offset: f1002.fbeOffset + f1002.fbeSize)
f1004 = FieldModelFlagsSimple(buffer: buffer, offset: f1003.fbeOffset + f1003.fbeSize)
f1005 = FieldModelOptionalFlagsSimple(buffer: buffer, offset: f1004.fbeOffset + f1004.fbeSize)
f1006 = FieldModelFlagsTyped(buffer: buffer, offset: f1005.fbeOffset + f1005.fbeSize)
f1007 = FieldModelOptionalFlagsTyped(buffer: buffer, offset: f1006.fbeOffset + f1006.fbeSize)
f1008 = FieldModelStructSimple(buffer: buffer, offset: f1007.fbeOffset + f1007.fbeSize)
f1009 = FieldModelOptionalStructSimple(buffer: buffer, offset: f1008.fbeOffset + f1008.fbeSize)
f1010 = FieldModelStructOptional(buffer: buffer, offset: f1009.fbeOffset + f1009.fbeSize)
f1011 = FieldModelOptionalStructOptional(buffer: buffer, offset: f1010.fbeOffset + f1010.fbeSize)
var fbeBody = (4 + 4)
fbeBody += parent.fbeBody - 4 - 4
fbeBody += f1000.fbeSize
fbeBody += f1001.fbeSize
fbeBody += f1002.fbeSize
fbeBody += f1003.fbeSize
fbeBody += f1004.fbeSize
fbeBody += f1005.fbeSize
fbeBody += f1006.fbeSize
fbeBody += f1007.fbeSize
fbeBody += f1008.fbeSize
fbeBody += f1009.fbeSize
fbeBody += f1010.fbeSize
fbeBody += f1011.fbeSize
self.fbeBody = fbeBody
}
// Field extra size
public var fbeExtra: Int {
if _buffer.offset + fbeOffset + fbeSize > _buffer.size {
return 0
}
let fbeStructOffset = Int(readUInt32(offset: fbeOffset))
if (fbeStructOffset == 0) || ((_buffer.offset + fbeStructOffset + 4) > _buffer.size) {
return 0
}
_buffer.shift(offset: fbeStructOffset)
var fbeResult = fbeBody
fbeResult += parent.fbeExtra
fbeResult += f1000.fbeExtra
fbeResult += f1001.fbeExtra
fbeResult += f1002.fbeExtra
fbeResult += f1003.fbeExtra
fbeResult += f1004.fbeExtra
fbeResult += f1005.fbeExtra
fbeResult += f1006.fbeExtra
fbeResult += f1007.fbeExtra
fbeResult += f1008.fbeExtra
fbeResult += f1009.fbeExtra
fbeResult += f1010.fbeExtra
fbeResult += f1011.fbeExtra
_buffer.unshift(offset: fbeStructOffset)
return fbeResult
}
// Field type
public var fbeType: Int = fbeTypeConst
public static let fbeTypeConst: Int = 112
// Check if the struct value is valid
func verify(fbeVerifyType: Bool = true) -> Bool {
if (_buffer.offset + fbeOffset + fbeSize) > _buffer.size {
return true
}
let fbeStructOffset = Int(readUInt32(offset: fbeOffset))
if (fbeStructOffset == 0) || ((_buffer.offset + fbeStructOffset + 4 + 4) > _buffer.size) {
return false
}
let fbeStructSize = Int(readUInt32(offset: fbeStructOffset))
if fbeStructSize < (4 + 4) {
return false
}
let fbeStructType = Int(readUInt32(offset: fbeStructOffset + 4))
if fbeVerifyType && (fbeStructType != fbeType) {
return false
}
_buffer.shift(offset: fbeStructOffset)
let fbeResult = verifyFields(fbeStructSize: fbeStructSize)
_buffer.unshift(offset: fbeStructOffset)
return fbeResult
}
// Check if the struct fields are valid
public func verifyFields(fbeStructSize: Int) -> Bool {
var fbeCurrentSize = 4 + 4
if fbeCurrentSize + parent.fbeBody - 4 - 4 > fbeStructSize {
return true
}
if !parent.verifyFields(fbeStructSize: fbeStructSize) {
return false
}
fbeCurrentSize += parent.fbeBody - 4 - 4
if (fbeCurrentSize + f1000.fbeSize) > fbeStructSize {
return true
}
if !f1000.verify() {
return false
}
fbeCurrentSize += f1000.fbeSize
if (fbeCurrentSize + f1001.fbeSize) > fbeStructSize {
return true
}
if !f1001.verify() {
return false
}
fbeCurrentSize += f1001.fbeSize
if (fbeCurrentSize + f1002.fbeSize) > fbeStructSize {
return true
}
if !f1002.verify() {
return false
}
fbeCurrentSize += f1002.fbeSize
if (fbeCurrentSize + f1003.fbeSize) > fbeStructSize {
return true
}
if !f1003.verify() {
return false
}
fbeCurrentSize += f1003.fbeSize
if (fbeCurrentSize + f1004.fbeSize) > fbeStructSize {
return true
}
if !f1004.verify() {
return false
}
fbeCurrentSize += f1004.fbeSize
if (fbeCurrentSize + f1005.fbeSize) > fbeStructSize {
return true
}
if !f1005.verify() {
return false
}
fbeCurrentSize += f1005.fbeSize
if (fbeCurrentSize + f1006.fbeSize) > fbeStructSize {
return true
}
if !f1006.verify() {
return false
}
fbeCurrentSize += f1006.fbeSize
if (fbeCurrentSize + f1007.fbeSize) > fbeStructSize {
return true
}
if !f1007.verify() {
return false
}
fbeCurrentSize += f1007.fbeSize
if (fbeCurrentSize + f1008.fbeSize) > fbeStructSize {
return true
}
if !f1008.verify() {
return false
}
fbeCurrentSize += f1008.fbeSize
if (fbeCurrentSize + f1009.fbeSize) > fbeStructSize {
return true
}
if !f1009.verify() {
return false
}
fbeCurrentSize += f1009.fbeSize
if (fbeCurrentSize + f1010.fbeSize) > fbeStructSize {
return true
}
if !f1010.verify() {
return false
}
fbeCurrentSize += f1010.fbeSize
if (fbeCurrentSize + f1011.fbeSize) > fbeStructSize {
return true
}
if !f1011.verify() {
return false
}
fbeCurrentSize += f1011.fbeSize
return true
}
// Get the struct value (begin phase)
func getBegin() -> Int {
if _buffer.offset + fbeOffset + fbeSize > _buffer.size {
return 0
}
let fbeStructOffset = Int(readUInt32(offset: fbeOffset))
if (fbeStructOffset == 0) || ((_buffer.offset + fbeStructOffset + 4 + 4) > _buffer.size) {
assertionFailure("Model is broken!")
return 0
}
let fbeStructSize = Int(readUInt32(offset: fbeStructOffset))
if fbeStructSize < 4 + 4 {
assertionFailure("Model is broken!")
return 0
}
_buffer.shift(offset: fbeStructOffset)
return fbeStructOffset
}
// Get the struct value (end phase)
func getEnd(fbeBegin: Int) {
_buffer.unshift(offset: fbeBegin)
}
// Get the struct value
public func get() -> StructNested {
var fbeValue = StructNested()
return get(fbeValue: &fbeValue)
}
public func get(fbeValue: inout StructNested) -> StructNested {
let fbeBegin = getBegin()
if fbeBegin == 0 {
return fbeValue
}
let fbeStructSize = Int(readUInt32(offset: 0))
getFields(fbeValue: &fbeValue, fbeStructSize: fbeStructSize)
getEnd(fbeBegin: fbeBegin)
return fbeValue
}
// Get the struct fields values
public func getFields(fbeValue: inout StructNested, fbeStructSize: Int) {
var fbeCurrentSize = 4 + 4
if fbeCurrentSize + parent.fbeBody - 4 - 4 <= fbeStructSize {
parent.getFields(fbeValue: &fbeValue.parent, fbeStructSize: fbeStructSize)
}
fbeCurrentSize += parent.fbeBody - 4 - 4
if fbeCurrentSize + f1000.fbeSize <= fbeStructSize {
fbeValue.f1000 = f1000.get()
} else {
fbeValue.f1000 = ChronoxorTest.EnumSimple()
}
fbeCurrentSize += f1000.fbeSize
if fbeCurrentSize + f1001.fbeSize <= fbeStructSize {
fbeValue.f1001 = f1001.get()
} else {
fbeValue.f1001 = nil
}
fbeCurrentSize += f1001.fbeSize
if fbeCurrentSize + f1002.fbeSize <= fbeStructSize {
fbeValue.f1002 = f1002.get(defaults: ChronoxorTest.EnumTyped.ENUM_VALUE_2)
} else {
fbeValue.f1002 = ChronoxorTest.EnumTyped.ENUM_VALUE_2
}
fbeCurrentSize += f1002.fbeSize
if fbeCurrentSize + f1003.fbeSize <= fbeStructSize {
fbeValue.f1003 = f1003.get(defaults: nil)
} else {
fbeValue.f1003 = nil
}
fbeCurrentSize += f1003.fbeSize
if fbeCurrentSize + f1004.fbeSize <= fbeStructSize {
fbeValue.f1004 = f1004.get()
} else {
fbeValue.f1004 = ChronoxorTest.FlagsSimple()
}
fbeCurrentSize += f1004.fbeSize
if fbeCurrentSize + f1005.fbeSize <= fbeStructSize {
fbeValue.f1005 = f1005.get()
} else {
fbeValue.f1005 = nil
}
fbeCurrentSize += f1005.fbeSize
if fbeCurrentSize + f1006.fbeSize <= fbeStructSize {
fbeValue.f1006 = f1006.get(defaults: FlagsTyped.fromSet(set: [FlagsTyped.FLAG_VALUE_2.value!, FlagsTyped.FLAG_VALUE_4.value!, FlagsTyped.FLAG_VALUE_6.value!]))
} else {
fbeValue.f1006 = FlagsTyped.fromSet(set: [FlagsTyped.FLAG_VALUE_2.value!, FlagsTyped.FLAG_VALUE_4.value!, FlagsTyped.FLAG_VALUE_6.value!])
}
fbeCurrentSize += f1006.fbeSize
if fbeCurrentSize + f1007.fbeSize <= fbeStructSize {
fbeValue.f1007 = f1007.get(defaults: nil)
} else {
fbeValue.f1007 = nil
}
fbeCurrentSize += f1007.fbeSize
if fbeCurrentSize + f1008.fbeSize <= fbeStructSize {
fbeValue.f1008 = f1008.get()
} else {
fbeValue.f1008 = ChronoxorTest.StructSimple()
}
fbeCurrentSize += f1008.fbeSize
if fbeCurrentSize + f1009.fbeSize <= fbeStructSize {
fbeValue.f1009 = f1009.get()
} else {
fbeValue.f1009 = nil
}
fbeCurrentSize += f1009.fbeSize
if fbeCurrentSize + f1010.fbeSize <= fbeStructSize {
fbeValue.f1010 = f1010.get()
} else {
fbeValue.f1010 = ChronoxorTest.StructOptional()
}
fbeCurrentSize += f1010.fbeSize
if fbeCurrentSize + f1011.fbeSize <= fbeStructSize {
fbeValue.f1011 = f1011.get(defaults: nil)
} else {
fbeValue.f1011 = nil
}
fbeCurrentSize += f1011.fbeSize
}
// Set the struct value (begin phase)
func setBegin() throws -> Int {
if (_buffer.offset + fbeOffset + fbeSize) > _buffer.size {
assertionFailure("Model is broken!")
return 0
}
let fbeStructSize = fbeBody
let fbeStructOffset = try _buffer.allocate(size: fbeStructSize) - _buffer.offset
if (fbeStructOffset <= 0) || ((_buffer.offset + fbeStructOffset + fbeStructSize) > _buffer.size) {
assertionFailure("Model is broken!")
return 0
}
write(offset: fbeOffset, value: UInt32(fbeStructOffset))
write(offset: fbeStructOffset, value: UInt32(fbeStructSize))
write(offset: fbeStructOffset + 4, value: UInt32(fbeType))
_buffer.shift(offset: fbeStructOffset)
return fbeStructOffset
}
// Set the struct value (end phase)
public func setEnd(fbeBegin: Int) {
_buffer.unshift(offset: fbeBegin)
}
// Set the struct value
public func set(value fbeValue: StructNested) throws {
let fbeBegin = try setBegin()
if fbeBegin == 0 {
return
}
try setFields(fbeValue: fbeValue)
setEnd(fbeBegin: fbeBegin)
}
// Set the struct fields values
public func setFields(fbeValue: StructNested) throws {
try parent.setFields(fbeValue: fbeValue.parent)
try f1000.set(value: fbeValue.f1000)
try f1001.set(value: fbeValue.f1001)
try f1002.set(value: fbeValue.f1002)
try f1003.set(value: fbeValue.f1003)
try f1004.set(value: fbeValue.f1004)
try f1005.set(value: fbeValue.f1005)
try f1006.set(value: fbeValue.f1006)
try f1007.set(value: fbeValue.f1007)
try f1008.set(value: fbeValue.f1008)
try f1009.set(value: fbeValue.f1009)
try f1010.set(value: fbeValue.f1010)
try f1011.set(value: fbeValue.f1011)
}
}
| 33.970954 | 171 | 0.608465 |
ffc2724f2befd9b1d18f18d7d8259801d1f64eee | 532 | import Flutter
import UIKit
public class SwiftAtNotifyFlutterPlugin: NSObject, FlutterPlugin {
public static func register(with registrar: FlutterPluginRegistrar) {
let channel = FlutterMethodChannel(name: "at_notify_flutter", binaryMessenger: registrar.messenger())
let instance = SwiftAtNotifyFlutterPlugin()
registrar.addMethodCallDelegate(instance, channel: channel)
}
public func handle(_ call: FlutterMethodCall, result: @escaping FlutterResult) {
result("iOS " + UIDevice.current.systemVersion)
}
}
| 35.466667 | 105 | 0.781955 |
163ce303a72516a42973fd07af99c7dd5bed5eea | 2,085 | //
// User.swift
// TWTRCDPTH
//
// Created by Niraj Pendal on 4/14/17.
// Copyright © 2017 Niraj. All rights reserved.
//
import Foundation
let currentUserKey = "currentUser"
class User {
var name: String?
var tagLine: String?
var profileURL: URL?
var screenName: String?
var tweets:[Tweet]?
private static var _currentUser:User?
static let userDidLogOutNotificationKey = "userDidLogOutNotification"
var _dictionary:[String:AnyObject]?
init(dictionary: [String:AnyObject]) {
self._dictionary = dictionary
name = dictionary ["name"] as? String
tagLine = dictionary ["description"] as? String
let profileString = dictionary ["profile_background_image_url_https"] as? String
if let profileStringNotNil = profileString {
profileURL = URL(string: profileStringNotNil)!
}
screenName = dictionary ["screen_name"] as? String
}
class var currentUser:User? {
get {
if _currentUser == nil {
let defaults = UserDefaults.standard
let userData = defaults.object(forKey: currentUserKey) as? Data
if let userData = userData {
let dictionary = try! JSONSerialization.jsonObject(with: userData, options: []) as! [String:AnyObject]
_currentUser = User(dictionary: dictionary)
}
}
return _currentUser
}
set(user) {
_currentUser = user
let defaults = UserDefaults.standard
if let user = user {
let data = try! JSONSerialization.data(withJSONObject: user._dictionary!, options: [])
defaults.set(data, forKey: currentUserKey)
} else {
defaults.set(nil, forKey: currentUserKey)
}
}
}
}
| 26.730769 | 122 | 0.536211 |
1e0737e0a5e3316fc71fbf0fec486b0cc3ffa3b5 | 5,554 | // Copyright © 2017 Square1.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import UIKit
/// Helpers for UIImage.
public extension UIImage {
/// Current UIImage bytes size.
var bytes: Int? {
return self.jpegData(compressionQuality: 1)?.count
}
/// Is image in portraint mode?
var isPortrait: Bool {
return imageOrientation == .left || imageOrientation == .right
}
/// Is image in landscape mode?
var isLandscape: Bool {
return imageOrientation == .up || imageOrientation == .down
}
/// Failable convenience init to create UIImage with passed UIColor.
///
/// - Parameters:
/// - color: Desired UIColor.
/// - size: Size for returned UIImage. By default, 1pt x 1pt.
convenience init?(color: UIColor, size: CGSize = CGSize(width: 1, height: 1)) {
let rect = CGRect(origin: .zero, size: size)
UIGraphicsBeginImageContextWithOptions(rect.size, false, 0.0)
color.setFill()
UIRectFill(rect)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
guard let cgImage = image?.cgImage else { return nil }
self.init(cgImage: cgImage)
}
/// Hack to fix image orientation when taking new photos.
///
/// - Returns: Fixed new photo.
func fixOrientation() -> UIImage {
guard imageOrientation != .up else { return self }
var transform: CGAffineTransform = CGAffineTransform.identity
switch imageOrientation {
case .down, .downMirrored:
transform = transform.translatedBy(x: size.width, y: size.height)
transform = transform.rotated(by: CGFloat(Double.pi))
break
case .left, .leftMirrored:
transform = transform.translatedBy(x: size.width, y: 0)
transform = transform.rotated(by: CGFloat(Double.pi / 2))
break
case .right, .rightMirrored:
transform = transform.translatedBy(x: 0, y: size.height)
transform = transform.rotated(by: CGFloat(-Double.pi / 2))
break
case .up, .upMirrored:
break
@unknown default:
break
}
switch imageOrientation {
case .upMirrored, .downMirrored:
transform.translatedBy(x: size.width, y: 0)
transform.scaledBy(x: -1, y: 1)
break
case .leftMirrored, .rightMirrored:
transform.translatedBy(x: size.height, y: 0)
transform.scaledBy(x: -1, y: 1)
case .up, .down, .left, .right:
break
@unknown default:
break
}
let ctx: CGContext = CGContext(data: nil, width: Int(size.width), height: Int(size.height), bitsPerComponent: self.cgImage!.bitsPerComponent, bytesPerRow: 0, space: (self.cgImage?.colorSpace)!, bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue)!
ctx.concatenate(transform)
switch imageOrientation {
case .left, .leftMirrored, .right, .rightMirrored:
ctx.draw(self.cgImage!, in: CGRect(x: 0, y: 0, width: size.height, height: size.width))
break
default:
ctx.draw(self.cgImage!, in: CGRect(x: 0, y: 0, width: size.width, height: size.height))
break
}
let cgImage: CGImage = ctx.makeImage()!
return UIImage(cgImage: cgImage)
}
/// Creates a tinted image with `color` of the current image
///
/// - Parameter color: color for tint
/// - Returns: new tinted image or same image of something goes wrong
func tintWith(color: UIColor) -> UIImage {
UIGraphicsBeginImageContextWithOptions(size, false, UIScreen.main.scale)
guard let context = UIGraphicsGetCurrentContext() else {
return self
}
//Flip image to avoid inverted result image
context.scaleBy(x: 1.0, y: -1.0)
context.translateBy(x: 0.0, y: -size.height)
context.setBlendMode(.multiply)
let rect = CGRect(x: 0, y: 0, width: size.width, height: size.height)
context.clip(to: rect, mask: cgImage!)
color.setFill()
context.fill(rect)
guard let image = UIGraphicsGetImageFromCurrentImageContext() else {
return self
}
UIGraphicsEndImageContext()
return image
}
}
| 37.527027 | 259 | 0.622254 |
16ead562ac3cb91870087ee9355652c1deaec53a | 10,813 | //
// VideoFiltersVC.swift
// YPImagePicker
//
// Created by Nik Kov || nik-kov.com on 18.04.2018.
// Copyright © 2018 Yummypets. All rights reserved.
//
import UIKit
import Photos
import PryntTrimmerView
public class YPVideoFiltersVC: UIViewController, IsMediaFilterVC {
@IBOutlet weak var trimBottomItem: YPMenuItem!
@IBOutlet weak var coverBottomItem: YPMenuItem!
@IBOutlet weak var videoView: YPVideoView!
@IBOutlet weak var trimmerView: TrimmerView!
@IBOutlet weak var coverImageView: UIImageView!
@IBOutlet weak var coverThumbSelectorView: ThumbSelectorView!
public var inputVideo: YPMediaVideo!
public var inputAsset: AVAsset { return AVAsset(url: inputVideo.url) }
private var playbackTimeCheckerTimer: Timer?
private var imageGenerator: AVAssetImageGenerator?
private var isFromSelectionVC = false
var didSave: ((YPMediaItem) -> Void)?
var didCancel: (() -> Void)?
/// Designated initializer
public class func initWith(video: YPMediaVideo,
isFromSelectionVC: Bool) -> YPVideoFiltersVC {
let vc = YPVideoFiltersVC(nibName: "YPVideoFiltersVC", bundle: Bundle(for: YPVideoFiltersVC.self))
vc.inputVideo = video
vc.isFromSelectionVC = isFromSelectionVC
return vc
}
// MARK: - Live cycle
override public func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = YPConfig.colors.filterBackgroundColor
trimmerView.mainColor = YPConfig.colors.trimmerMainColor
trimmerView.handleColor = YPConfig.colors.trimmerHandleColor
trimmerView.positionBarColor = YPConfig.colors.positionLineColor
trimmerView.maxDuration = YPConfig.video.trimmerMaxDuration
trimmerView.minDuration = YPConfig.video.trimmerMinDuration
coverThumbSelectorView.thumbBorderColor = YPConfig.colors.coverSelectorBorderColor
trimBottomItem.textLabel.text = YPConfig.wordings.trim
coverBottomItem.textLabel.text = YPConfig.wordings.cover
trimBottomItem.button.addTarget(self, action: #selector(selectTrim), for: .touchUpInside)
coverBottomItem.button.addTarget(self, action: #selector(selectCover), for: .touchUpInside)
// Remove the default and add a notification to repeat playback from the start
videoView.removeReachEndObserver()
NotificationCenter.default
.addObserver(self,
selector: #selector(itemDidFinishPlaying(_:)),
name: .AVPlayerItemDidPlayToEndTime,
object: nil)
// Set initial video cover
imageGenerator = AVAssetImageGenerator(asset: self.inputAsset)
imageGenerator?.appliesPreferredTrackTransform = true
didChangeThumbPosition(CMTime(seconds: 1, preferredTimescale: 1))
// Navigation bar setup
title = YPConfig.wordings.trim
if isFromSelectionVC {
navigationItem.leftBarButtonItem = UIBarButtonItem(title: YPConfig.wordings.cancel,
style: .plain,
target: self,
action: #selector(cancel))
navigationItem.leftBarButtonItem?.setFont(font: YPConfig.fonts.leftBarButtonFont, forState: .normal)
navigationItem.leftBarButtonItem?.tintColor = YPConfig.colors.tintColor
}
setupRightBarButtonItem()
}
override public func viewDidAppear(_ animated: Bool) {
trimmerView.asset = inputAsset
trimmerView.delegate = self
coverThumbSelectorView.asset = inputAsset
coverThumbSelectorView.delegate = self
selectTrim()
videoView.loadVideo(inputVideo)
super.viewDidAppear(animated)
}
public override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
stopPlaybackTimeChecker()
videoView.stop()
}
func setupRightBarButtonItem() {
let rightBarButtonTitle = isFromSelectionVC ? YPConfig.wordings.done : YPConfig.wordings.next
navigationItem.rightBarButtonItem = UIBarButtonItem(title: rightBarButtonTitle,
style: .done,
target: self,
action: #selector(save))
navigationItem.rightBarButtonItem?.tintColor = YPConfig.colors.tintColor
navigationItem.rightBarButtonItem?.setFont(font: YPConfig.fonts.rightBarButtonFont, forState: .normal)
}
// MARK: - Top buttons
@objc public func save() {
guard let didSave = didSave else { return print("Don't have saveCallback") }
navigationItem.rightBarButtonItem = YPLoaders.defaultLoader
do {
let asset = AVURLAsset(url: inputVideo.url)
let trimmedAsset = try asset
.assetByTrimming(startTime: trimmerView.startTime ?? CMTime.zero,
endTime: trimmerView.endTime ?? inputAsset.duration)
// Looks like file:///private/var/mobile/Containers/Data/Application
// /FAD486B4-784D-4397-B00C-AD0EFFB45F52/tmp/8A2B410A-BD34-4E3F-8CB5-A548A946C1F1.mov
let destinationURL = URL(fileURLWithPath: NSTemporaryDirectory())
.appendingUniquePathComponent(pathExtension: YPConfig.video.fileType.fileExtension)
_ = trimmedAsset.export(to: destinationURL) { [weak self] session in
switch session.status {
case .completed:
DispatchQueue.main.async {
if let coverImage = self?.coverImageView.image {
let resultVideo = YPMediaVideo(thumbnail: coverImage,
videoURL: destinationURL,
asset: self?.inputVideo.asset)
didSave(YPMediaItem.video(v: resultVideo))
self?.setupRightBarButtonItem()
} else {
print("YPVideoFiltersVC -> Don't have coverImage.")
}
}
case .failed:
print("YPVideoFiltersVC Export of the video failed. Reason: \(String(describing: session.error))")
default:
print("YPVideoFiltersVC Export session completed with \(session.status) status. Not handled")
}
}
} catch let error {
print("💩 \(error)")
}
}
@objc func cancel() {
didCancel?()
}
// MARK: - Bottom buttons
@objc public func selectTrim() {
title = YPConfig.wordings.trim
trimBottomItem.select()
coverBottomItem.deselect()
trimmerView.isHidden = false
videoView.isHidden = false
coverImageView.isHidden = true
coverThumbSelectorView.isHidden = true
}
@objc public func selectCover() {
title = YPConfig.wordings.cover
trimBottomItem.deselect()
coverBottomItem.select()
trimmerView.isHidden = true
videoView.isHidden = true
coverImageView.isHidden = false
coverThumbSelectorView.isHidden = false
stopPlaybackTimeChecker()
videoView.stop()
}
// MARK: - Various Methods
// Updates the bounds of the cover picker if the video is trimmed
// TODO: Now the trimmer framework doesn't support an easy way to do this.
// Need to rethink a flow or search other ways.
func updateCoverPickerBounds() {
if let startTime = trimmerView.startTime,
let endTime = trimmerView.endTime {
if let selectedCoverTime = coverThumbSelectorView.selectedTime {
let range = CMTimeRange(start: startTime, end: endTime)
if !range.containsTime(selectedCoverTime) {
// If the selected before cover range is not in new trimeed range,
// than reset the cover to start time of the trimmed video
}
} else {
// If none cover time selected yet, than set the cover to the start time of the trimmed video
}
}
}
// MARK: - Trimmer playback
@objc func itemDidFinishPlaying(_ notification: Notification) {
if let startTime = trimmerView.startTime {
videoView.player.seek(to: startTime)
}
}
func startPlaybackTimeChecker() {
stopPlaybackTimeChecker()
playbackTimeCheckerTimer = Timer
.scheduledTimer(timeInterval: 0.05, target: self,
selector: #selector(onPlaybackTimeChecker),
userInfo: nil,
repeats: true)
}
func stopPlaybackTimeChecker() {
playbackTimeCheckerTimer?.invalidate()
playbackTimeCheckerTimer = nil
}
@objc func onPlaybackTimeChecker() {
guard let startTime = trimmerView.startTime,
let endTime = trimmerView.endTime else {
return
}
let playBackTime = videoView.player.currentTime()
trimmerView.seek(to: playBackTime)
if playBackTime >= endTime {
videoView.player.seek(to: startTime,
toleranceBefore: CMTime.zero,
toleranceAfter: CMTime.zero)
trimmerView.seek(to: startTime)
}
}
}
// MARK: - TrimmerViewDelegate
extension YPVideoFiltersVC: TrimmerViewDelegate {
public func positionBarStoppedMoving(_ playerTime: CMTime) {
videoView.player.seek(to: playerTime, toleranceBefore: CMTime.zero, toleranceAfter: CMTime.zero)
videoView.play()
startPlaybackTimeChecker()
updateCoverPickerBounds()
}
public func didChangePositionBar(_ playerTime: CMTime) {
stopPlaybackTimeChecker()
videoView.pause()
videoView.player.seek(to: playerTime, toleranceBefore: CMTime.zero, toleranceAfter: CMTime.zero)
}
}
// MARK: - ThumbSelectorViewDelegate
extension YPVideoFiltersVC: ThumbSelectorViewDelegate {
public func didChangeThumbPosition(_ imageTime: CMTime) {
if let imageGenerator = imageGenerator,
let imageRef = try? imageGenerator.copyCGImage(at: imageTime, actualTime: nil) {
coverImageView.image = UIImage(cgImage: imageRef)
}
}
}
| 38.756272 | 118 | 0.608712 |
649663ba96da83ed55ee20783f7c812a02e03f94 | 552 | //
// HKBloodType+StringRepresentation.swift
//
// Created by Tomáš on 13.09.17.
//
import HealthKit
extension HKBloodType {
var stringRepresentation: String {
switch self {
case .notSet: return "Unknown"
case .aPositive: return "A+"
case .aNegative: return "A-"
case .bPositive: return "B+"
case .bNegative: return "B-"
case .abPositive: return "AB+"
case .abNegative: return "AB-"
case .oPositive: return "O+"
case .oNegative: return "O-"
}
}
}
| 22.08 | 42 | 0.577899 |
87b98a55c407709df509e59d67875cda2cc7469d | 1,245 | //
// TipSeeUITests.swift
// TipSeeUITests
//
// Created by Kavita Gaitonde on 8/6/17.
// Copyright © 2017 Kavita Gaitonde. All rights reserved.
//
import XCTest
class TipSeeUITests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
// In UI tests it is usually best to stop immediately when a failure occurs.
continueAfterFailure = false
// UI tests must launch the application that they test. Doing this in setup will make sure it happens for each test method.
XCUIApplication().launch()
// In UI tests it’s important to set the initial state - such as interface orientation - required for your tests before they run. The setUp method is a good place to do this.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testExample() {
// Use recording to get started writing UI tests.
// Use XCTAssert and related functions to verify your tests produce the correct results.
}
}
| 33.648649 | 182 | 0.662651 |
0a193207e3624c8baab0ffbd36921fde103dc579 | 799 | //
// ColorsView.swift
// ColorPicker
//
// Created by Andre Simon on 20-04-20.
// Copyright © 2020 Andre Simon. All rights reserved.
//
import SwiftUI
struct ColorsView: View {
@Binding var pickedColors: [UIColor]
var body: some View {
ScrollView(.vertical, showsIndicators: false) {
ForEach(pickedColors.indices, id: \.self) { idx in
ColorView(color: Color(self.pickedColors[idx]))
.frame(width: 30, height: 30)
.padding(.all)
.onTapGesture {
self.pickedColors.remove(at: idx)
}
}
}
}
}
struct ColorsView_Previews: PreviewProvider {
static var previews: some View {
ColorsView(pickedColors: Binding.constant([]))
}
}
| 24.212121 | 63 | 0.56821 |
3ae71b8132f3dc3a6ed0140f8e2ccd88c3f8d5ee | 2,037 | //
// AppCoordinator.swift
// facile
//
// Created by Renaud Pradenc on 16/10/2018.
//
import Foundation
class AppCoordinator {
let rootViewController: UIViewController
let businessFilesList: BusinessFilesList
let officeCoordinator: OfficeCoordinator
let scanCoordinator: ScanCoordinator
let sidePanelController: SidePanelController
init(rootViewController: UIViewController, businessFilesList: BusinessFilesList, sidePanelController: SidePanelController, officeCoordinator: OfficeCoordinator, scanCoordinator: ScanCoordinator) {
self.rootViewController = rootViewController
self.businessFilesList = businessFilesList
self.officeCoordinator = officeCoordinator
self.scanCoordinator = scanCoordinator
self.sidePanelController = sidePanelController
officeCoordinator.delegate = self;
scanCoordinator.delegate = self
// If there is a saved Session, this forces the initial loading.
// When loaded, the first BusinessFile will be selected and a notification sent.
forceLoadingBusinessFilesList()
NotificationCenter.default.addObserver(forName: NSNotification.Name.FCLSessionDidSignIn, object: nil, queue: nil) { [weak self] (_) in
self?.forceLoadingBusinessFilesList()
}
}
private func forceLoadingBusinessFilesList() {
MBProgressHUD.showAdded(to: rootViewController.view, animated: true)
businessFilesList.getBusinessFiles { [weak self] (_) in
DispatchQueue.main.async {
MBProgressHUD.hide(for: self?.rootViewController.view, animated: true)
}
}
}
}
extension AppCoordinator: OfficeCoordinatorDelegate {
func officeCoordinatorPresentSidePanel() {
sidePanelController.present(from: rootViewController)
}
}
extension AppCoordinator: ScanCoordinatorDelegate {
func scanCoordinatorPresentSidePanel() {
sidePanelController.present(from: rootViewController)
}
}
| 35.736842 | 200 | 0.719686 |
89bb0266717fde3d6cff7afa633c1d743e795c64 | 3,088 | /*
* Copyright (C) 2016 Fred Rajaona
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import Foundation
public protocol ScannerListener {
var listenerHashValue: String { get }
func onScannedButtonsChanged(_ scannedButtons: [String: FlicButton])
}
public class Scanner {
private let session: FlicSession
private let scanId: UInt32
private var scannedButtons = [String: FlicButton]()
private var scanning = false
public var isScanning: Bool {
return scanning
}
private var listeners = [String: ScannerListener]()
init(flicSession: FlicSession, id: UInt32) {
session = flicSession
scanId = id
}
public func start() {
if !scanning {
scanning = true
let startCommand = getCommand(FlicCommand.CommandType.createScanner)
session.sendMessage(startCommand.message)
}
}
public func stop() {
if scanning {
scanning = false
let stopCommand = getCommand(FlicCommand.CommandType.removeScanner)
session.sendMessage(stopCommand.message)
scannedButtons.removeAll()
}
}
public func registerListener(_ listener: ScannerListener) {
if listeners[listener.listenerHashValue] == nil {
listeners[listener.listenerHashValue] = listener
}
listener.onScannedButtonsChanged(scannedButtons)
}
public func unregisterListener(_ listener: ScannerListener) {
listeners[listener.listenerHashValue] = nil
}
func notifyListeners() {
for (_, listener) in listeners {
listener.onScannedButtonsChanged(scannedButtons)
}
}
func handleEvent(_ event: FlicEvent) {
switch event.eventType {
case .advertisementPacket:
if let data = event.payload {
let buttonInfo = ScanButtonInfo(fromData: data as Data, isAdvertisement: true)
if let button = scannedButtons[buttonInfo.name] {
button.update(buttonInfo)
} else {
scannedButtons[buttonInfo.name] = FlicButton(info: buttonInfo, flicSession: session)
}
}
default:
break
}
}
private func getCommand(_ commandType: FlicCommand.CommandType) -> FlicCommand {
let data = NSMutableData()
var id = scanId
data.append(&id, length: 4)
return FlicCommand(commandType: commandType, data: data as Data)
}
}
| 30.574257 | 104 | 0.63342 |
5dbd73c3bd908458589b775431cf9eaf27683621 | 1,358 | import UIKit
import Foundation
func pullNewMovies(genre: String, number: Int, completion: @escaping ([String: Any]) -> ()) {
if let url = URL(string: "https://api.reelgood.com/v3.0/content/roulette/netflix?availability=onAnySource&content_kind=both&nocache=true®ion=us") {
URLSession.shared.dataTask(with: url) { (data, response, err) in
if err != nil {
print(err ?? "Error")
completion([" ": " "])
}
guard let data = data else { return }
do {
// make sure this JSON is in the format we expect
if let json = try JSONSerialization.jsonObject(with: data, options: []) as? [String: Any] {
completion(json)
// if (json["message"] as? String == "Not Found") {
// completion(f[alse)
// } else {
// completion(true)
// }
}
} catch _ {
completion([" ": " "])
}
}.resume()
}
}
for i in 0...10 {
pullNewMovies(genre: "", number: 0, completion: { yuh in
print(yuh)
})
}
| 36.702703 | 154 | 0.42268 |
fc8c1bc54d7335340d21a2875e589dc2e0cd2839 | 280 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
let A {
{
}
protocol c {
{
}
let t: Any {
}
}
class A {
func a<T where B : A {
}
class B<T where g: a {
func a
| 14.736842 | 87 | 0.675 |
11765431842bd6033375b1825ddb7569b463a1c6 | 169 | //
// Validator.swift
// SwiftBBS
//
// Created by Takeo Namba on 2016/02/02.
// Copyright GrooveLab
//
protocol Validator {
func validate(value: Any?) throws
} | 15.363636 | 41 | 0.662722 |
14b3187fba27a0d850a0f63dee3714b9345f14d7 | 4,025 | //===----------------------------------------------------------------------===//
//
// This source file is part of the AWSSDKSwift open source project
//
// Copyright (c) 2017-2020 the AWSSDKSwift project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of AWSSDKSwift project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
// THIS FILE IS AUTOMATICALLY GENERATED by https://github.com/swift-aws/aws-sdk-swift/blob/master/CodeGenerator/Sources/CodeGenerator/main.swift. DO NOT EDIT.
import AWSSDKSwiftCore
/// Error enum for EventBridge
public enum EventBridgeErrorType: AWSErrorType {
case concurrentModificationException(message: String?)
case internalException(message: String?)
case invalidEventPatternException(message: String?)
case invalidStateException(message: String?)
case limitExceededException(message: String?)
case managedRuleException(message: String?)
case operationDisabledException(message: String?)
case policyLengthExceededException(message: String?)
case resourceAlreadyExistsException(message: String?)
case resourceNotFoundException(message: String?)
}
extension EventBridgeErrorType {
public init?(errorCode: String, message: String?) {
var errorCode = errorCode
if let index = errorCode.firstIndex(of: "#") {
errorCode = String(errorCode[errorCode.index(index, offsetBy: 1)...])
}
switch errorCode {
case "ConcurrentModificationException":
self = .concurrentModificationException(message: message)
case "InternalException":
self = .internalException(message: message)
case "InvalidEventPatternException":
self = .invalidEventPatternException(message: message)
case "InvalidStateException":
self = .invalidStateException(message: message)
case "LimitExceededException":
self = .limitExceededException(message: message)
case "ManagedRuleException":
self = .managedRuleException(message: message)
case "OperationDisabledException":
self = .operationDisabledException(message: message)
case "PolicyLengthExceededException":
self = .policyLengthExceededException(message: message)
case "ResourceAlreadyExistsException":
self = .resourceAlreadyExistsException(message: message)
case "ResourceNotFoundException":
self = .resourceNotFoundException(message: message)
default:
return nil
}
}
}
extension EventBridgeErrorType: CustomStringConvertible {
public var description: String {
switch self {
case .concurrentModificationException(let message):
return "ConcurrentModificationException: \(message ?? "")"
case .internalException(let message):
return "InternalException: \(message ?? "")"
case .invalidEventPatternException(let message):
return "InvalidEventPatternException: \(message ?? "")"
case .invalidStateException(let message):
return "InvalidStateException: \(message ?? "")"
case .limitExceededException(let message):
return "LimitExceededException: \(message ?? "")"
case .managedRuleException(let message):
return "ManagedRuleException: \(message ?? "")"
case .operationDisabledException(let message):
return "OperationDisabledException: \(message ?? "")"
case .policyLengthExceededException(let message):
return "PolicyLengthExceededException: \(message ?? "")"
case .resourceAlreadyExistsException(let message):
return "ResourceAlreadyExistsException: \(message ?? "")"
case .resourceNotFoundException(let message):
return "ResourceNotFoundException: \(message ?? "")"
}
}
}
| 43.75 | 158 | 0.659627 |
4a77d3852ac198e13c7d38bbbb40b41599953083 | 778 | //
// TransitionEssential.swift
// FYPhoto
//
// Created by xiaoyang on 2021/2/5.
//
import Foundation
/// Transition animation needs these infos to find out which image to show and where is it.
public struct TransitionEssential {
let transitionImage: UIImage?
/// frame coverted to viewController view
let convertedFrame: CGRect
/// Initial essentials
/// - Parameters:
/// - transitionImage: Transition uses the image for animation
/// - convertedFrame: Location of the image in the ViewController. e.g., imageView.convert(imageView.bounds, to: viewControllerView)
public init(transitionImage: UIImage?, convertedFrame: CGRect) {
self.transitionImage = transitionImage
self.convertedFrame = convertedFrame
}
}
| 31.12 | 138 | 0.710797 |
e4487f6f4fce10c9803ee7f21f5f71ca63ee0882 | 823 | import Foundation
import Shared
final class CustomObjectNameRetainer: SourceGraphVisitor {
static func make(graph: SourceGraph) -> Self {
return self.init(graph: graph, configuration: inject())
}
private let graph: SourceGraph
private let configuration: Configuration
required init(graph: SourceGraph, configuration: Configuration) {
self.graph = graph
self.configuration = configuration
}
func visit() {
graph
.declarations(ofKinds: [.class, .struct])
.lazy
.filter {
if let name = $0.name {
return self.configuration.retainObjects.contains(name)
} else {
return true
}
}
.forEach(graph.markRetained)
}
}
| 25.71875 | 74 | 0.572296 |
9ba2c2123c6f4ced173a07a9d860d8c46c2eda13 | 127 | import XCTest
import SwiftPaillierTests
var tests = [XCTestCaseEntry]()
tests += SwiftPaillierTests.allTests()
XCTMain(tests) | 18.142857 | 38 | 0.80315 |
ff9a0bfb4dba1abc27d414ea495ffefeb8b46faa | 54,331 | // RUN: %empty-directory(%t)
// RUN: %target-swift-frontend -emit-module -emit-module-path %t/OtherActors.swiftmodule -module-name OtherActors %S/Inputs/OtherActors.swift -disable-availability-checking
// RUN: %target-typecheck-verify-swift -I %t -disable-availability-checking -warn-concurrency
// REQUIRES: concurrency
import OtherActors // expected-remark{{add '@preconcurrency' to suppress 'Sendable'-related warnings from module 'OtherActors'}}{{1-1=@preconcurrency }}
let immutableGlobal: String = "hello"
var mutableGlobal: String = "can't touch this" // expected-note 5{{var declared here}}
@available(SwiftStdlib 5.1, *)
func globalFunc() { }
@available(SwiftStdlib 5.1, *)
func acceptClosure<T>(_: () -> T) { }
@available(SwiftStdlib 5.1, *)
func acceptConcurrentClosure<T>(_: @Sendable () -> T) { }
@available(SwiftStdlib 5.1, *)
func acceptEscapingClosure<T>(_: @escaping () -> T) { }
@available(SwiftStdlib 5.1, *)
func acceptEscapingClosure<T>(_: @escaping (String) -> ()) async -> T? { nil }
@available(SwiftStdlib 5.1, *)
@discardableResult func acceptAsyncClosure<T>(_: () async -> T) -> T { }
@available(SwiftStdlib 5.1, *)
func acceptEscapingAsyncClosure<T>(_: @escaping () async -> T) { }
@available(SwiftStdlib 5.1, *)
func acceptInout<T>(_: inout T) {}
// ----------------------------------------------------------------------
// Actor state isolation restrictions
// ----------------------------------------------------------------------
@available(SwiftStdlib 5.1, *)
actor MySuperActor {
var superState: Int = 25 // expected-note {{mutation of this property is only permitted within the actor}}
func superMethod() { // expected-note {{calls to instance method 'superMethod()' from outside of its actor context are implicitly asynchronous}}
self.superState += 5
}
func superAsyncMethod() async { }
subscript (index: Int) -> String {
"\(index)"
}
}
class Point { // expected-note 5{{class 'Point' does not conform to the 'Sendable' protocol}}
var x : Int = 0
var y : Int = 0
}
@available(SwiftStdlib 5.1, *)
actor MyActor: MySuperActor { // expected-error{{actor types do not support inheritance}}
let immutable: Int = 17
// expected-note@+2 2{{property declared here}}
// expected-note@+1 6{{mutation of this property is only permitted within the actor}}
var mutable: Int = 71
// expected-note@+2 3 {{mutation of this property is only permitted within the actor}}
// expected-note@+1 4{{property declared here}}
var text: [String] = []
let point : Point = Point()
@MainActor
var name : String = "koala" // expected-note{{property declared here}}
func accessProp() -> String {
return self.name // expected-error{{property 'name' isolated to global actor 'MainActor' can not be referenced from actor 'MyActor' in a synchronous context}}
}
static func synchronousClass() { }
static func synchronousStatic() { }
func synchronous() -> String { text.first ?? "nothing" } // expected-note 9{{calls to instance method 'synchronous()' from outside of its actor context are implicitly asynchronous}}
func asynchronous() async -> String {
super.superState += 4
return synchronous()
}
}
@available(SwiftStdlib 5.1, *)
actor Camera {
func accessProp(act : MyActor) async -> String {
return await act.name
}
}
@available(SwiftStdlib 5.1, *)
func checkAsyncPropertyAccess() async {
let act = MyActor()
let _ : Int = await act.mutable + act.mutable
act.mutable += 1 // expected-error {{actor-isolated property 'mutable' can not be mutated from a non-isolated context}}
act.superState += 1 // expected-error {{actor-isolated property 'superState' can not be mutated from a non-isolated context}}
act.text[0].append("hello") // expected-error{{actor-isolated property 'text' can not be mutated from a non-isolated context}}
// this is not the same as the above, because Array is a value type
var arr = await act.text
arr[0].append("hello")
act.text.append("no") // expected-error{{actor-isolated property 'text' can not be mutated from a non-isolated context}}
act.text[0] += "hello" // expected-error{{actor-isolated property 'text' can not be mutated from a non-isolated context}}
_ = act.point // expected-warning{{non-sendable type 'Point' in asynchronous access to actor-isolated property 'point' cannot cross actor boundary}}
}
/// ------------------------------------------------------------------
/// -- Value types do not need isolation on their stored properties --
protocol MainCounter {
@MainActor var counter: Int { get set }
@MainActor var ticker: Int { get set }
}
struct InferredFromConformance: MainCounter {
var counter = 0
var ticker: Int {
get { 1 }
set {}
}
}
@MainActor
struct InferredFromContext {
var point = Point()
var polygon: [Point] {
get { [] }
}
nonisolated var status: Bool = true // expected-error {{'nonisolated' can not be applied to stored properties}}{{3-15=}}
nonisolated let flag: Bool = false // expected-warning {{'nonisolated' is redundant on struct's stored properties; this is an error in Swift 6}}{{3-15=}}
subscript(_ i: Int) -> Int { return i }
static var stuff: [Int] = []
}
func checkIsolationValueType(_ formance: InferredFromConformance,
_ ext: InferredFromContext,
_ anno: NoGlobalActorValueType) async {
// these still do need an await in Swift 5
_ = await ext.point // expected-warning {{non-sendable type 'Point' in implicitly asynchronous access to main actor-isolated property 'point' cannot cross actor boundary}}
_ = await formance.counter
_ = await anno.point // expected-warning {{non-sendable type 'Point' in implicitly asynchronous access to global actor 'SomeGlobalActor'-isolated property 'point' cannot cross actor boundary}}
_ = anno.counter
// these will always need an await
_ = await (formance as MainCounter).counter
_ = await ext[1]
_ = await formance.ticker
_ = await ext.polygon // expected-warning {{non-sendable type '[Point]' in implicitly asynchronous access to main actor-isolated property 'polygon' cannot cross actor boundary}}
_ = await InferredFromContext.stuff
_ = await NoGlobalActorValueType.polygon // expected-warning {{non-sendable type '[Point]' in implicitly asynchronous access to main actor-isolated static property 'polygon' cannot cross actor boundary}}
}
// check for instance members that do not need global-actor protection
struct NoGlobalActorValueType {
@SomeGlobalActor var point: Point // expected-warning {{stored property 'point' within struct cannot have a global actor; this is an error in Swift 6}}
@MainActor let counter: Int // expected-warning {{stored property 'counter' within struct cannot have a global actor; this is an error in Swift 6}}
@MainActor static var polygon: [Point] = []
}
/// -----------------------------------------------------------------
@available(SwiftStdlib 5.1, *)
extension MyActor {
nonisolated var actorIndependentVar: Int {
get { 5 }
set { }
}
nonisolated func actorIndependentFunc(otherActor: MyActor) -> Int {
_ = immutable
_ = mutable // expected-error{{actor-isolated property 'mutable' can not be referenced from a non-isolated}}
_ = text[0] // expected-error{{actor-isolated property 'text' can not be referenced from a non-isolated context}}
_ = synchronous() // expected-error{{actor-isolated instance method 'synchronous()' can not be referenced from a non-isolated context}}
// nonisolated
_ = actorIndependentFunc(otherActor: self)
_ = actorIndependentVar
actorIndependentVar = 17
_ = self.actorIndependentFunc(otherActor: self)
_ = self.actorIndependentVar
self.actorIndependentVar = 17
// nonisolated on another actor
_ = otherActor.actorIndependentFunc(otherActor: self)
_ = otherActor.actorIndependentVar
otherActor.actorIndependentVar = 17
// async promotion
_ = synchronous() // expected-error{{actor-isolated instance method 'synchronous()' can not be referenced from a non-isolated context}}
// Global actors
syncGlobalActorFunc() /// expected-error{{call to global actor 'SomeGlobalActor'-isolated global function 'syncGlobalActorFunc()' in a synchronous nonisolated context}}
_ = syncGlobalActorFunc
// Global data is okay if it is immutable.
_ = immutableGlobal
_ = mutableGlobal // expected-warning{{reference to var 'mutableGlobal' is not concurrency-safe because it involves shared mutable state}}
// Partial application
_ = synchronous // expected-error{{actor-isolated instance method 'synchronous()' can not be partially applied}}
_ = super.superMethod // expected-error{{actor-isolated instance method 'superMethod()' can not be referenced from a non-isolated context}}
acceptClosure(synchronous) // expected-error{{actor-isolated instance method 'synchronous()' can not be referenced from a non-isolated context}}
acceptClosure(self.synchronous) // expected-error{{actor-isolated instance method 'synchronous()' can not be referenced from a non-isolated context}}
acceptClosure(otherActor.synchronous) // expected-error{{actor-isolated instance method 'synchronous()' can not be referenced from a non-isolated context}}
acceptEscapingClosure(synchronous) // expected-error{{actor-isolated instance method 'synchronous()' can not be partially applied}}
acceptEscapingClosure(self.synchronous) // expected-error{{actor-isolated instance method 'synchronous()' can not be partially applied}}
acceptEscapingClosure(otherActor.synchronous) // expected-error{{actor-isolated instance method 'synchronous()' can not be partially applied}}
return 5
}
func testAsynchronous(otherActor: MyActor) async {
_ = immutable
_ = mutable
mutable = 0
_ = synchronous()
_ = text[0]
acceptInout(&mutable)
// Accesses on 'self' are okay.
_ = self.immutable
_ = self.mutable
self.mutable = 0
_ = self.synchronous()
_ = await self.asynchronous()
_ = self.text[0]
acceptInout(&self.mutable)
_ = self[0]
// Accesses on 'super' are okay.
_ = super.superState
super.superState = 0
acceptInout(&super.superState)
super.superMethod()
await super.superAsyncMethod()
_ = super[0]
// Accesses on other actors can only reference immutable data synchronously,
// otherwise the access is treated as async
_ = otherActor.immutable // okay
_ = otherActor.mutable // expected-error{{expression is 'async' but is not marked with 'await'}}{{9-9=await }}
// expected-note@-1{{property access is 'async'}}
_ = await otherActor.mutable
otherActor.mutable = 0 // expected-error{{actor-isolated property 'mutable' can not be mutated on a non-isolated actor instance}}
acceptInout(&otherActor.mutable) // expected-error{{actor-isolated property 'mutable' can not be used 'inout' on a non-isolated actor instance}}
// expected-error@+2{{actor-isolated property 'mutable' can not be mutated on a non-isolated actor instance}}
// expected-warning@+1{{no 'async' operations occur within 'await' expression}}
await otherActor.mutable = 0
_ = otherActor.synchronous()
// expected-error@-1{{expression is 'async' but is not marked with 'await'}}{{9-9=await }}
// expected-note@-2{{calls to instance method 'synchronous()' from outside of its actor context are implicitly asynchronous}}
_ = await otherActor.asynchronous()
_ = otherActor.text[0]
// expected-error@-1{{expression is 'async' but is not marked with 'await'}}{{9-9=await }}
// expected-note@-2{{property access is 'async'}}
_ = await otherActor.text[0] // okay
// Global data is okay if it is immutable.
_ = immutableGlobal
_ = mutableGlobal // expected-warning{{reference to var 'mutableGlobal' is not concurrency-safe because it involves shared mutable state}}
// Global functions are not actually safe, but we allow them for now.
globalFunc()
// Class methods are okay.
Self.synchronousClass()
Self.synchronousStatic()
// Global actors
syncGlobalActorFunc() // expected-error{{expression is 'async' but is not marked with 'await'}}{{5-5=await }}
// expected-note@-1{{calls to global function 'syncGlobalActorFunc()' from outside of its actor context are implicitly asynchronous}}
await asyncGlobalActorFunc()
// Closures.
let localConstant = 17
var localVar = 17
// Non-escaping closures are okay.
acceptClosure {
_ = text[0]
_ = self.synchronous()
_ = localVar
_ = localConstant
}
// Concurrent closures might run... concurrently.
var otherLocalVar = 12
acceptConcurrentClosure { [otherLocalVar] in
defer {
_ = otherLocalVar
}
_ = self.text[0] // expected-error{{actor-isolated property 'text' can not be referenced from a Sendable closure}}
_ = self.mutable // expected-error{{actor-isolated property 'mutable' can not be referenced from a Sendable closure}}
self.mutable = 0 // expected-error{{actor-isolated property 'mutable' can not be mutated from a Sendable closure}}
acceptInout(&self.mutable) // expected-error{{actor-isolated property 'mutable' can not be used 'inout' from a Sendable closure}}
_ = self.immutable
_ = self.synchronous() // expected-error{{actor-isolated instance method 'synchronous()' can not be referenced from a Sendable closure}}
_ = localVar // expected-error{{reference to captured var 'localVar' in concurrently-executing code}}
localVar = 25 // expected-error{{mutation of captured var 'localVar' in concurrently-executing code}}
_ = localConstant
_ = otherLocalVar
}
otherLocalVar = 17
acceptConcurrentClosure { [weak self, otherLocalVar] in
defer {
_ = self?.actorIndependentVar
}
_ = otherLocalVar
}
// Escaping closures are still actor-isolated
acceptEscapingClosure {
_ = self.text[0]
_ = self.mutable
self.mutable = 0
acceptInout(&self.mutable)
_ = self.immutable
_ = self.synchronous()
_ = localVar
_ = localConstant
}
// Local functions might run concurrently.
@Sendable func localFn1() {
_ = self.text[0] // expected-error{{actor-isolated property 'text' can not be referenced from a Sendable function}}
_ = self.synchronous() // expected-error{{actor-isolated instance method 'synchronous()' can not be referenced from a Sendable function}}
_ = localVar // expected-error{{reference to captured var 'localVar' in concurrently-executing code}}
localVar = 25 // expected-error{{mutation of captured var 'localVar' in concurrently-executing code}}
_ = localConstant
}
@Sendable func localFn2() {
acceptClosure {
_ = text[0] // expected-error{{actor-isolated property 'text' can not be referenced from a non-isolated context}}
_ = self.synchronous() // expected-error{{actor-isolated instance method 'synchronous()' can not be referenced from a non-isolated context}}
_ = localVar // expected-error{{reference to captured var 'localVar' in concurrently-executing code}}
localVar = 25 // expected-error{{mutation of captured var 'localVar' in concurrently-executing code}}
_ = localConstant
}
}
acceptEscapingClosure {
localFn1()
localFn2()
}
localVar = 0
// Partial application
_ = synchronous
_ = super.superMethod
acceptClosure(synchronous)
acceptClosure(self.synchronous)
acceptClosure(otherActor.synchronous) // expected-error{{actor-isolated instance method 'synchronous()' can not be referenced on a non-isolated actor instance}}
acceptEscapingClosure(synchronous)
acceptEscapingClosure(self.synchronous)
acceptEscapingClosure(otherActor.synchronous) // expected-error{{actor-isolated instance method 'synchronous()' can not be partially applied}}
acceptAsyncClosure(self.asynchronous)
acceptEscapingAsyncClosure(self.asynchronous)
}
}
// ----------------------------------------------------------------------
// Global actor isolation restrictions
// ----------------------------------------------------------------------
@available(SwiftStdlib 5.1, *)
actor SomeActor { }
@globalActor
@available(SwiftStdlib 5.1, *)
struct SomeGlobalActor {
static let shared = SomeActor()
}
@globalActor
@available(SwiftStdlib 5.1, *)
struct SomeOtherGlobalActor {
static let shared = SomeActor()
}
@globalActor
@available(SwiftStdlib 5.1, *)
struct GenericGlobalActor<T> {
static var shared: SomeActor { SomeActor() }
}
@available(SwiftStdlib 5.1, *)
@SomeGlobalActor func onions() {} // expected-note{{calls to global function 'onions()' from outside of its actor context are implicitly asynchronous}}
@available(SwiftStdlib 5.1, *)
@MainActor func beets() { onions() } // expected-error{{call to global actor 'SomeGlobalActor'-isolated global function 'onions()' in a synchronous main actor-isolated context}}
// expected-note@-1{{calls to global function 'beets()' from outside of its actor context are implicitly asynchronous}}
@available(SwiftStdlib 5.1, *)
actor Crystal {
// expected-note@+2 {{property declared here}}
// expected-note@+1 2 {{mutation of this property is only permitted within the actor}}
@SomeGlobalActor var globActorVar : Int = 0
// expected-note@+1 {{mutation of this property is only permitted within the actor}}
@SomeGlobalActor var globActorProp : Int {
get { return 0 }
set {}
}
@SomeGlobalActor func foo(_ x : inout Int) {}
func referToGlobProps() async {
_ = await globActorVar + globActorProp
globActorProp = 20 // expected-error {{property 'globActorProp' isolated to global actor 'SomeGlobalActor' can not be mutated from actor 'Crystal'}}
globActorVar = 30 // expected-error {{property 'globActorVar' isolated to global actor 'SomeGlobalActor' can not be mutated from actor 'Crystal'}}
// expected-error@+2 {{property 'globActorVar' isolated to global actor 'SomeGlobalActor' can not be used 'inout' from actor 'Crystal'}}
// expected-error@+1 {{actor-isolated property 'globActorVar' cannot be passed 'inout' to implicitly 'async' function call}}
await self.foo(&globActorVar)
_ = self.foo
}
}
@available(SwiftStdlib 5.1, *)
@SomeGlobalActor func syncGlobalActorFunc() { syncGlobalActorFunc() } // expected-note {{calls to global function 'syncGlobalActorFunc()' from outside of its actor context are implicitly asynchronous}}
@available(SwiftStdlib 5.1, *)
@SomeGlobalActor func asyncGlobalActorFunc() async { await asyncGlobalActorFunc() }
@available(SwiftStdlib 5.1, *)
@SomeOtherGlobalActor func syncOtherGlobalActorFunc() { }
@available(SwiftStdlib 5.1, *)
@SomeOtherGlobalActor func asyncOtherGlobalActorFunc() async {
await syncGlobalActorFunc()
await asyncGlobalActorFunc()
}
@available(SwiftStdlib 5.1, *)
func testGlobalActorClosures() {
let _: Int = acceptAsyncClosure { @SomeGlobalActor in
syncGlobalActorFunc()
syncOtherGlobalActorFunc() // expected-error{{expression is 'async' but is not marked with 'await'}}{{5-5=await }}
// expected-note@-1{{calls to global function 'syncOtherGlobalActorFunc()' from outside of its actor context are implicitly asynchronous}}
await syncOtherGlobalActorFunc()
return 17
}
acceptConcurrentClosure { @SomeGlobalActor in 5 } // expected-warning{{converting function value of type '@SomeGlobalActor @Sendable () -> Int' to '@Sendable () -> Int' loses global actor 'SomeGlobalActor'}}
}
@available(SwiftStdlib 5.1, *)
extension MyActor {
@SomeGlobalActor func onGlobalActor(otherActor: MyActor) async {
// Access to other functions in this actor are okay.
syncGlobalActorFunc()
await asyncGlobalActorFunc()
// Other global actors are ok if marked with 'await'
await syncOtherGlobalActorFunc()
await asyncOtherGlobalActorFunc()
_ = immutable
_ = mutable // expected-error{{expression is 'async' but is not marked with 'await'}}{{9-9=await }}
// expected-note@-1{{property access is 'async'}}
_ = await mutable
_ = synchronous() // expected-error{{expression is 'async' but is not marked with 'await'}}{{9-9=await }}
// expected-note@-1{{calls to instance method 'synchronous()' from outside of its actor context are implicitly asynchronous}}
_ = await synchronous()
_ = text[0] // expected-error{{expression is 'async' but is not marked with 'await'}}
// expected-note@-1{{property access is 'async'}}
_ = await text[0]
// Accesses on 'self' are only okay for immutable and asynchronous, because
// we are outside of the actor instance.
_ = self.immutable
_ = self.synchronous() // expected-error{{expression is 'async' but is not marked with 'await'}}{{9-9=await }}
// expected-note@-1{{calls to instance method 'synchronous()' from outside of its actor context are implicitly asynchronous}}
_ = await self.synchronous()
_ = await self.asynchronous()
_ = self.text[0] // expected-error{{expression is 'async' but is not marked with 'await'}}{{9-9=await }}
// expected-note@-1{{property access is 'async'}}
_ = self[0] // expected-error{{expression is 'async' but is not marked with 'await'}}{{9-9=await }}
// expected-note@-1{{subscript access is 'async'}}
_ = await self.text[0]
_ = await self[0]
// Accesses on 'super' are not okay without 'await'; we're outside of the actor.
_ = super.superState // expected-error{{expression is 'async' but is not marked with 'await'}}{{9-9=await }}
// expected-note@-1{{property access is 'async'}}
_ = await super.superState
super.superMethod() // expected-error{{expression is 'async' but is not marked with 'await'}}{{5-5=await }}
// expected-note@-1{{calls to instance method 'superMethod()' from outside of its actor context are implicitly asynchronous}}
await super.superMethod()
await super.superAsyncMethod()
_ = super[0] // expected-error{{expression is 'async' but is not marked with 'await'}}{{9-9=await }}
// expected-note@-1{{subscript access is 'async'}}
_ = await super[0]
// Accesses on other actors can only reference immutable data or
// call asynchronous methods
_ = otherActor.immutable // okay
_ = otherActor.synchronous() // expected-error{{expression is 'async' but is not marked with 'await'}}{{9-9=await }}
// expected-note@-1{{calls to instance method 'synchronous()' from outside of its actor context are implicitly asynchronous}}
_ = otherActor.synchronous // expected-error{{actor-isolated instance method 'synchronous()' can not be partially applied}}
_ = await otherActor.asynchronous()
_ = otherActor.text[0] // expected-error{{expression is 'async' but is not marked with 'await'}}{{9-9=await }}
// expected-note@-1{{property access is 'async'}}
_ = await otherActor.text[0]
}
}
func testBadImplicitGlobalActorClosureCall() async {
{ @MainActor in }() // expected-error{{expression is 'async' but is not marked with 'await'}}
// expected-note@-1{{calls function of type '@MainActor () -> ()' from outside of its actor context are implicitly asynchronous}}
}
@available(SwiftStdlib 5.1, *)
struct GenericStruct<T> {
@GenericGlobalActor<T> func f() { } // expected-note {{calls to instance method 'f()' from outside of its actor context are implicitly asynchronous}}
@GenericGlobalActor<T> func g() {
f() // okay
}
@GenericGlobalActor<String> func h() {
f() // expected-error{{call to global actor 'GenericGlobalActor<T>'-isolated instance method 'f()' in a synchronous global actor 'GenericGlobalActor<String>'-isolated context}}
let fn = f // expected-note{{calls to let 'fn' from outside of its actor context are implicitly asynchronous}}
fn() // expected-error{{call to global actor 'GenericGlobalActor<T>'-isolated let 'fn' in a synchronous global actor 'GenericGlobalActor<String>'-isolated context}}
}
}
@available(SwiftStdlib 5.1, *)
extension GenericStruct where T == String {
@GenericGlobalActor<T>
func h2() {
f()
g()
h()
}
}
@SomeGlobalActor
var number: Int = 42 // expected-note {{var declared here}}
// expected-note@+1 {{add '@SomeGlobalActor' to make global function 'badNumberUser()' part of global actor 'SomeGlobalActor'}}
func badNumberUser() {
//expected-error@+1{{var 'number' isolated to global actor 'SomeGlobalActor' can not be referenced from this synchronous context}}
print("The protected number is: \(number)")
}
@available(SwiftStdlib 5.1, *)
func asyncBadNumberUser() async {
print("The protected number is: \(await number)")
}
// ----------------------------------------------------------------------
// Non-actor code isolation restrictions
// ----------------------------------------------------------------------
@available(SwiftStdlib 5.1, *)
func testGlobalRestrictions(actor: MyActor) async {
let _ = MyActor()
// references to sync methods must be fully applied.
_ = actor.synchronous // expected-error{{actor-isolated instance method 'synchronous()' can not be partially applied}}
_ = actor.asynchronous
// any kind of method can be called from outside the actor, so long as it's marked with 'await'
_ = actor.synchronous() // expected-error{{expression is 'async' but is not marked with 'await'}}{{7-7=await }}
// expected-note@-1{{calls to instance method 'synchronous()' from outside of its actor context are implicitly asynchronous}}
_ = actor.asynchronous() // expected-error{{expression is 'async' but is not marked with 'await'}}{{7-7=await }}
// expected-note@-1{{call is 'async'}}
_ = await actor.synchronous()
_ = await actor.asynchronous()
// stored and computed properties can be accessed. Only immutable stored properties can be accessed without 'await'
_ = actor.immutable
_ = await actor.immutable // expected-warning {{no 'async' operations occur within 'await' expression}}
_ = actor.mutable // expected-error{{expression is 'async' but is not marked with 'await'}}{{7-7=await }}
// expected-note@-1{{property access is 'async'}}
_ = await actor.mutable
_ = actor.text[0] // expected-error{{expression is 'async' but is not marked with 'await'}}{{7-7=await }}
// expected-note@-1{{property access is 'async'}}
_ = await actor.text[0]
_ = actor[0] // expected-error{{expression is 'async' but is not marked with 'await'}}{{7-7=await }}
// expected-note@-1{{subscript access is 'async'}}
_ = await actor[0]
// nonisolated declarations are permitted.
_ = actor.actorIndependentFunc(otherActor: actor)
_ = actor.actorIndependentVar
actor.actorIndependentVar = 5
// Operations on non-instances are permitted.
MyActor.synchronousStatic()
MyActor.synchronousClass()
// Global mutable state cannot be accessed.
_ = mutableGlobal // expected-warning{{reference to var 'mutableGlobal' is not concurrency-safe because it involves shared mutable state}}
// Local mutable variables cannot be accessed from concurrently-executing
// code.
var i = 17
acceptConcurrentClosure {
_ = i // expected-error{{reference to captured var 'i' in concurrently-executing code}}
i = 42 // expected-error{{mutation of captured var 'i' in concurrently-executing code}}
}
print(i)
acceptConcurrentClosure { [i] in
_ = i
}
print("\(number)") //expected-error {{expression is 'async' but is not marked with 'await'}}{{12-12=await }}
//expected-note@-1{{property access is 'async'}}
}
@available(SwiftStdlib 5.1, *)
func f() {
acceptConcurrentClosure {
_ = mutableGlobal // expected-warning{{reference to var 'mutableGlobal' is not concurrency-safe because it involves shared mutable state}}
}
@Sendable func g() {
_ = mutableGlobal // expected-warning{{reference to var 'mutableGlobal' is not concurrency-safe because it involves shared mutable state}}
}
}
// ----------------------------------------------------------------------
// Local function isolation restrictions
// ----------------------------------------------------------------------
@available(SwiftStdlib 5.1, *)
actor AnActorWithClosures {
var counter: Int = 0 // expected-note 2 {{mutation of this property is only permitted within the actor}}
func exec() {
acceptEscapingClosure { [unowned self] in
self.counter += 1
acceptEscapingClosure {
self.counter += 1
acceptEscapingClosure { [self] in
self.counter += 1
}
acceptConcurrentClosure { [self] in
self.counter += 1 // expected-error{{actor-isolated property 'counter' can not be mutated from a Sendable closure}}
acceptEscapingClosure {
self.counter += 1 // expected-error{{actor-isolated property 'counter' can not be mutated from a non-isolated context}}
}
}
}
}
}
}
// ----------------------------------------------------------------------
// Local function isolation restrictions
// ----------------------------------------------------------------------
@available(SwiftStdlib 5.1, *)
func checkLocalFunctions() async {
var i = 0
var j = 0
func local1() {
i = 17
}
func local2() { // expected-error{{concurrently-executed local function 'local2()' must be marked as '@Sendable'}}{{3-3=@Sendable }}
j = 42
}
// Okay to call locally.
local1()
local2()
// non-sendable closures don't cause problems.
acceptClosure {
local1()
local2()
}
// Escaping closures can make the local function execute concurrently.
acceptConcurrentClosure {
local2() // expected-warning{{capture of 'local2()' with non-sendable type '() -> ()' in a `@Sendable` closure}}
// expected-note@-1{{a function type must be marked '@Sendable' to conform to 'Sendable'}}
}
print(i)
print(j)
var k = 17
func local4() {
acceptConcurrentClosure {
local3() // expected-warning{{capture of 'local3()' with non-sendable type '() -> ()' in a `@Sendable` closure}}
// expected-note@-1{{a function type must be marked '@Sendable' to conform to 'Sendable'}}
}
}
func local3() { // expected-error{{concurrently-executed local function 'local3()' must be marked as '@Sendable'}}
k = 25 // expected-error{{mutation of captured var 'k' in concurrently-executing code}}
}
print(k)
}
@available(SwiftStdlib 5.1, *)
actor LocalFunctionIsolatedActor {
func a() -> Bool { // expected-note{{calls to instance method 'a()' from outside of its actor context are implicitly asynchronous}}
return true
}
func b() -> Bool {
func c() -> Bool {
return true && a() // okay, c is isolated
}
return c()
}
func b2() -> Bool {
@Sendable func c() -> Bool {
return true && a() // expected-error{{actor-isolated instance method 'a()' can not be referenced from a non-isolated context}}
}
return c()
}
}
// ----------------------------------------------------------------------
// Lazy properties with initializers referencing 'self'
// ----------------------------------------------------------------------
@available(SwiftStdlib 5.1, *)
actor LazyActor {
var v: Int = 0
// expected-note@-1 6 {{property declared here}}
let l: Int = 0
lazy var l11: Int = { v }()
lazy var l12: Int = v
lazy var l13: Int = { self.v }()
lazy var l14: Int = self.v
lazy var l15: Int = { [unowned self] in self.v }() // expected-error{{actor-isolated property 'v' can not be referenced from a non-isolated context}}
lazy var l21: Int = { l }()
lazy var l22: Int = l
lazy var l23: Int = { self.l }()
lazy var l24: Int = self.l
lazy var l25: Int = { [unowned self] in self.l }()
nonisolated lazy var l31: Int = { v }()
// expected-error@-1 {{actor-isolated property 'v' can not be referenced from a non-isolated context}}
nonisolated lazy var l32: Int = v
// expected-error@-1 {{actor-isolated property 'v' can not be referenced from a non-isolated context}}
nonisolated lazy var l33: Int = { self.v }()
// expected-error@-1 {{actor-isolated property 'v' can not be referenced from a non-isolated context}}
nonisolated lazy var l34: Int = self.v
// expected-error@-1 {{actor-isolated property 'v' can not be referenced from a non-isolated context}}
nonisolated lazy var l35: Int = { [unowned self] in self.v }()
// expected-error@-1 {{actor-isolated property 'v' can not be referenced from a non-isolated context}}
nonisolated lazy var l41: Int = { l }()
nonisolated lazy var l42: Int = l
nonisolated lazy var l43: Int = { self.l }()
nonisolated lazy var l44: Int = self.l
nonisolated lazy var l45: Int = { [unowned self] in self.l }()
}
// Infer global actors from context only for instance members.
@available(SwiftStdlib 5.1, *)
@MainActor
class SomeClassInActor {
enum ID: String { case best }
func inActor() { } // expected-note{{calls to instance method 'inActor()' from outside of its actor context are implicitly asynchronous}}
}
@available(SwiftStdlib 5.1, *)
extension SomeClassInActor.ID {
func f(_ object: SomeClassInActor) { // expected-note{{add '@MainActor' to make instance method 'f' part of global actor 'MainActor'}}
object.inActor() // expected-error{{call to main actor-isolated instance method 'inActor()' in a synchronous nonisolated context}}
}
}
// ----------------------------------------------------------------------
// Initializers (through typechecking only)
// ----------------------------------------------------------------------
@available(SwiftStdlib 5.1, *)
actor SomeActorWithInits {
var mutableState: Int = 17 // expected-note 2 {{mutation of this property is only permitted within the actor}}
var otherMutableState: Int
let nonSendable: SomeClass
// Sema should not complain about referencing non-sendable members
// in an actor init or deinit, as those are diagnosed later by flow-isolation.
init(_ x: SomeClass) {
self.nonSendable = x
}
init(i1: Bool) {
self.mutableState = 42
self.otherMutableState = 17
self.isolated() // expected-error{{actor-isolated instance method 'isolated()' can not be referenced from a non-isolated context}}
self.nonisolated()
defer {
isolated() // expected-error{{actor-isolated instance method 'isolated()' can not be referenced from a non-isolated context}}
mutableState += 1 // okay
nonisolated()
}
func local() {
isolated() // expected-error{{actor-isolated instance method 'isolated()' can not be referenced from a non-isolated context}}
mutableState += 1 // expected-error{{actor-isolated property 'mutableState' can not be mutated from a non-isolated context}}
nonisolated()
}
local()
let _ = {
defer {
isolated() // expected-error{{actor-isolated instance method 'isolated()' can not be referenced from a non-isolated context}}
mutableState += 1 // expected-error{{actor-isolated property 'mutableState' can not be mutated from a non-isolated context}}
nonisolated()
}
nonisolated()
}()
}
init(i2: Bool) async {
self.mutableState = 0
self.otherMutableState = 1
self.isolated()
self.nonisolated()
}
convenience init(i3: Bool) {
self.init(i1: i3)
self.isolated() // expected-error{{actor-isolated instance method 'isolated()' can not be referenced from a non-isolated context}}
self.nonisolated()
}
convenience init(i4: Bool) async {
self.init(i1: i4)
self.isolated()
self.nonisolated()
}
@MainActor init(i5 x: SomeClass) {
self.mutableState = 42
self.otherMutableState = 17
self.nonSendable = x
self.isolated() // expected-error{{actor-isolated instance method 'isolated()' can not be referenced from the main actor}}
self.nonisolated()
}
@MainActor init(i6: Bool) async {
self.mutableState = 42
self.otherMutableState = 17
await self.isolated()
self.nonisolated()
}
@MainActor convenience init(i7: Bool) {
self.init(i1: i7)
self.isolated() // expected-error{{actor-isolated instance method 'isolated()' can not be referenced from the main actor}}
self.nonisolated()
}
@MainActor convenience init(i8: Bool) async {
self.init(i1: i8)
await self.isolated()
self.nonisolated()
}
deinit {
let _ = self.nonSendable // OK only through typechecking, not SIL.
defer {
isolated() // expected-warning{{actor-isolated instance method 'isolated()' can not be referenced from a non-isolated deinit; this is an error in Swift 6}}
mutableState += 1 // okay
nonisolated()
}
let _ = {
defer {
isolated() // expected-warning{{actor-isolated instance method 'isolated()' can not be referenced from a non-isolated closure; this is an error in Swift 6}}
mutableState += 1 // expected-warning{{actor-isolated property 'mutableState' can not be referenced from a non-isolated closure; this is an error in Swift 6}}
nonisolated()
}
nonisolated()
}()
}
func isolated() { } // expected-note 7 {{calls to instance method 'isolated()' from outside of its actor context are implicitly asynchronous}}
nonisolated func nonisolated() {}
}
@available(SwiftStdlib 5.1, *)
@MainActor
class SomeClassWithInits {
var mutableState: Int = 17
var otherMutableState: Int
static var shared = SomeClassWithInits() // expected-note 2{{static property declared here}}
init() { // expected-note{{calls to initializer 'init()' from outside of its actor context are implicitly asynchronous}}
self.mutableState = 42
self.otherMutableState = 17
self.isolated()
}
deinit {
print(mutableState) // Okay, we're actor-isolated
print(SomeClassWithInits.shared) // expected-error{{static property 'shared' isolated to global actor 'MainActor' can not be referenced from this synchronous context}}
beets() //expected-error{{call to main actor-isolated global function 'beets()' in a synchronous nonisolated context}}
}
func isolated() { }
static func staticIsolated() { // expected-note{{calls to static method 'staticIsolated()' from outside of its actor context are implicitly asynchronous}}
_ = SomeClassWithInits.shared
}
func hasDetached() {
Task.detached {
// okay
await self.isolated()
self.isolated()
// expected-error@-1{{expression is 'async' but is not marked with 'await'}}{{7-7=await }}
// expected-note@-2{{calls to instance method 'isolated()' from outside of its actor context are implicitly asynchronous}}
print(await self.mutableState)
}
}
}
@available(SwiftStdlib 5.1, *)
func outsideSomeClassWithInits() { // expected-note 3 {{add '@MainActor' to make global function 'outsideSomeClassWithInits()' part of global actor 'MainActor'}}
_ = SomeClassWithInits() // expected-error{{call to main actor-isolated initializer 'init()' in a synchronous nonisolated context}}
_ = SomeClassWithInits.shared // expected-error{{static property 'shared' isolated to global actor 'MainActor' can not be referenced from this synchronous context}}
SomeClassWithInits.staticIsolated() // expected-error{{call to main actor-isolated static method 'staticIsolated()' in a synchronous nonisolated context}}
}
// ----------------------------------------------------------------------
// nonisolated let and cross-module let
// ----------------------------------------------------------------------
func testCrossModuleLets(actor: OtherModuleActor) async {
_ = actor.a // expected-error{{expression is 'async' but is not marked with 'await'}}
// expected-note@-1{{property access is 'async'}}
_ = await actor.a // okay
_ = actor.b // okay
_ = actor.c // expected-error{{expression is 'async' but is not marked with 'await'}}
// expected-note@-1{{property access is 'async'}}
// expected-warning@-2{{non-sendable type 'SomeClass' in implicitly asynchronous access to actor-isolated property 'c' cannot cross actor boundary}}
_ = await actor.c // expected-warning{{non-sendable type 'SomeClass' in implicitly asynchronous access to actor-isolated property 'c' cannot cross actor boundary}}
_ = await actor.d // okay
}
func testCrossModuleAsIsolated(actor: isolated OtherModuleActor) {
_ = actor.a
_ = actor.b
_ = actor.c
_ = actor.d
}
extension OtherModuleActor {
func testCrossModuleInExtension() {
_ = self.a
_ = self.b
_ = self.c
_ = self.d
}
}
actor CrossModuleFromInitsActor {
init(v1 actor: OtherModuleActor) {
_ = actor.a // expected-error {{actor-isolated property 'a' can not be referenced from a non-isolated context}}
_ = actor.b // okay
_ = actor.c // expected-error {{actor-isolated property 'c' can not be referenced from a non-isolated context}}
}
init(v2 actor: OtherModuleActor) async {
_ = actor.a // expected-error{{expression is 'async' but is not marked with 'await'}}
// expected-note@-1{{property access is 'async'}}
_ = await actor.a // okay
_ = actor.b // okay
_ = actor.c // expected-error{{expression is 'async' but is not marked with 'await'}}
// expected-note@-1{{property access is 'async'}}
// expected-warning@-2{{non-sendable type 'SomeClass' in implicitly asynchronous access to actor-isolated property 'c' cannot cross actor boundary}}
_ = await actor.c // expected-warning{{non-sendable type 'SomeClass' in implicitly asynchronous access to actor-isolated property 'c' cannot cross actor boundary}}
_ = await actor.d // okay
}
}
// ----------------------------------------------------------------------
// Actor protocols.
// ----------------------------------------------------------------------
@available(SwiftStdlib 5.1, *)
actor A: Actor { // ok
}
@available(SwiftStdlib 5.1, *)
class C: Actor, UnsafeSendable {
// expected-error@-1{{non-actor type 'C' cannot conform to the 'Actor' protocol}}
// expected-warning@-2{{'UnsafeSendable' is deprecated: Use @unchecked Sendable instead}}
nonisolated var unownedExecutor: UnownedSerialExecutor {
fatalError()
}
}
@available(SwiftStdlib 5.1, *)
protocol P: Actor {
func f()
}
@available(SwiftStdlib 5.1, *)
extension P {
func g() { f() }
}
@available(SwiftStdlib 5.1, *)
actor MyActorP: P {
func f() { }
func h() { g() }
}
@available(SwiftStdlib 5.1, *)
protocol SP {
static func s()
}
@available(SwiftStdlib 5.1, *)
actor ASP: SP {
static func s() { }
}
@available(SwiftStdlib 5.1, *)
protocol SPD {
static func sd()
}
@available(SwiftStdlib 5.1, *)
extension SPD {
static func sd() { }
}
@available(SwiftStdlib 5.1, *)
actor ASPD: SPD {
}
@available(SwiftStdlib 5.1, *)
func testCrossActorProtocol<T: P>(t: T) async {
await t.f()
await t.g()
t.f()
// expected-error@-1{{expression is 'async' but is not marked with 'await'}}{{3-3=await }}
// expected-note@-2{{calls to instance method 'f()' from outside of its actor context are implicitly asynchronous}}
t.g()
// expected-error@-1{{expression is 'async' but is not marked with 'await'}}{{3-3=await }}
// expected-note@-2{{calls to instance method 'g()' from outside of its actor context are implicitly asynchronous}}
ASP.s()
ASPD.sd()
}
@available(SwiftStdlib 5.1, *)
protocol Server {
func send<Message: Codable & Sendable>(message: Message) async throws -> String
}
@available(SwiftStdlib 5.1, *)
actor MyServer : Server {
// okay, asynchronously accessed from clients of the protocol
func send<Message: Codable & Sendable>(message: Message) throws -> String { "" }
}
// ----------------------------------------------------------------------
// @_inheritActorContext
// ----------------------------------------------------------------------
@available(SwiftStdlib 5.1, *)
func acceptAsyncSendableClosure<T>(_: @Sendable () async -> T) { }
@available(SwiftStdlib 5.1, *)
func acceptAsyncSendableClosureInheriting<T>(@_inheritActorContext _: @Sendable () async -> T) { }
@available(SwiftStdlib 5.1, *)
extension MyActor {
func testSendableAndInheriting() {
var counter = 0
acceptAsyncSendableClosure {
_ = synchronous() // expected-error{{expression is 'async' but is not marked with 'await'}}
// expected-note@-1{{calls to instance method 'synchronous()' from outside of its actor context are implicitly asynchronous}}
counter += 1 // expected-error{{mutation of captured var 'counter' in concurrently-executing code}}
}
acceptAsyncSendableClosure {
_ = await synchronous() // ok
counter += 1 // expected-error{{mutation of captured var 'counter' in concurrently-executing code}}
}
acceptAsyncSendableClosureInheriting {
_ = synchronous() // okay
counter += 1 // okay
}
acceptAsyncSendableClosureInheriting {
_ = await synchronous() // expected-warning{{no 'async' operations occur within 'await' expression}}
counter += 1 // okay
}
}
}
@available(SwiftStdlib 5.1, *)
@SomeGlobalActor
func testGlobalActorInheritance() {
var counter = 0
acceptAsyncSendableClosure {
counter += 1 // expected-error{{mutation of captured var 'counter' in concurrently-executing code}}
}
acceptAsyncSendableClosure { @SomeGlobalActor in
counter += 1 // ok
}
acceptAsyncSendableClosureInheriting {
counter += 1 // ok
}
}
@available(SwiftStdlib 5.1, *)
@MainActor // expected-note {{'GloballyIsolatedProto' is isolated to global actor 'MainActor' here}}
protocol GloballyIsolatedProto {
}
// rdar://75849035 - trying to conform an actor to a global-actor isolated protocol should result in an error
func test_conforming_actor_to_global_actor_protocol() {
@available(SwiftStdlib 5.1, *)
actor MyValue : GloballyIsolatedProto {}
// expected-error@-1 {{actor 'MyValue' cannot conform to global actor isolated protocol 'GloballyIsolatedProto'}}
}
func test_invalid_reference_to_actor_member_without_a_call_note() {
actor A {
func partial() { }
}
actor Test {
func returnPartial(other: A) async -> () async -> () {
let a = other.partial
// expected-error@-1 {{actor-isolated instance method 'partial()' can not be partially applied}}
return a
}
}
}
// Actor isolation and initializers through typechecking only, not flow-isolation.
actor Counter {
var counter: Int = 0
// expected-note@+2{{mutation of this property is only permitted within the actor}}
// expected-note@+1{{property declared here}}
var computedProp : Int {
get { 0 }
set { }
}
func next() -> Int { // expected-note 2 {{calls to instance method 'next()' from outside of its actor context are implicitly asynchronous}}
defer {
counter = counter + 1
}
return counter
}
func localNext() -> Int {
func doIt() {
counter = counter + 1
}
doIt()
return counter
}
init() {
_ = self.next() // expected-error {{actor-isolated instance method 'next()' can not be referenced from a non-isolated context}}
defer { _ = self.next() } // expected-error {{actor-isolated instance method 'next()' can not be referenced from a non-isolated context}}
_ = computedProp // expected-error {{actor-isolated property 'computedProp' can not be referenced from a non-isolated context}}
computedProp = 1 // expected-error {{actor-isolated property 'computedProp' can not be mutated from a non-isolated context}}
}
convenience init(material: Int) async {
self.init()
self.counter = 10 // FIXME: this should work, and also needs to work in definite initialization by injecting hops
}
}
/// Superclass checks for global actor-qualified class types.
class C2 { }
@SomeGlobalActor
class C3: C2 { } // it's okay to add a global actor to a nonisolated class.
@GenericGlobalActor<U>
class GenericSuper<U> { }
@GenericGlobalActor<[T]>
class GenericSub1<T>: GenericSuper<[T]> { }
@GenericGlobalActor<T>
class GenericSub2<T>: GenericSuper<[T]> { } // expected-error{{global actor 'GenericGlobalActor<T>'-isolated class 'GenericSub2' has different actor isolation from global actor 'GenericGlobalActor<U>'-isolated superclass 'GenericSuper'}}
/// Diagnostics for `nonisolated` on an actor initializer.
actor Butterfly {
var flapsPerSec = 0 // expected-note 3{{mutation of this property is only permitted within the actor}}
nonisolated init() {} // expected-warning {{'nonisolated' on an actor's synchronous initializer is invalid; this is an error in Swift 6}} {{3-15=}}
nonisolated init(async: Void) async {}
nonisolated convenience init(icecream: Void) { // expected-warning {{'nonisolated' on an actor's synchronous initializer is invalid; this is an error in Swift 6}} {{3-15=}}
self.init()
self.flapsPerSec += 1 // expected-error {{actor-isolated property 'flapsPerSec' can not be mutated from a non-isolated context}}
}
nonisolated convenience init(cookies: Void) async {
self.init()
self.flapsPerSec += 1 // expected-error {{actor-isolated property 'flapsPerSec' can not be mutated from a non-isolated context}}
}
convenience init(brownies: Void) {
self.init()
self.flapsPerSec = 0 // expected-error {{actor-isolated property 'flapsPerSec' can not be mutated from a non-isolated context}}
}
}
// expected-note@+1 2 {{calls to global function 'takeIsolated' from outside of its actor context are implicitly asynchronous}}
func takeIsolated(_ val: isolated SelfParamIsolationNonMethod) {}
func take(_ val: SelfParamIsolationNonMethod) {}
actor SelfParamIsolationNonMethod {
init(s0: Void) {
// expected-note@+2 {{calls to instance method 'f()' from outside of its actor context are implicitly asynchronous}}
// expected-error@+1 {{expression is 'async' but is not marked with 'await'}}
acceptAsyncSendableClosureInheriting { self.f() }
// expected-note@+2 {{calls to instance method 'f()' from outside of its actor context are implicitly asynchronous}}
// expected-error@+1 {{expression is 'async' but is not marked with 'await'}}
acceptAsyncSendableClosure { self.f() }
// expected-error@+1 {{call to actor-isolated global function 'takeIsolated' in a synchronous nonisolated context}}
takeIsolated(self)
take(self)
}
@MainActor init(s1: Void) {
// expected-note@+2 {{calls to instance method 'f()' from outside of its actor context are implicitly asynchronous}}
// expected-error@+1 {{expression is 'async' but is not marked with 'await'}}
acceptAsyncSendableClosureInheriting { self.f() }
// expected-note@+2 {{calls to instance method 'f()' from outside of its actor context are implicitly asynchronous}}
// expected-error@+1 {{expression is 'async' but is not marked with 'await'}}
acceptAsyncSendableClosure { self.f() }
}
init(a1: Void) async {
acceptAsyncSendableClosureInheriting { self.f() }
// expected-note@+2 {{calls to instance method 'f()' from outside of its actor context are implicitly asynchronous}}
// expected-error@+1 {{expression is 'async' but is not marked with 'await'}}
acceptAsyncSendableClosure { self.f() }
takeIsolated(self)
take(self)
}
@MainActor init(a2: Void) async {
// expected-note@+2 {{calls to instance method 'f()' from outside of its actor context are implicitly asynchronous}}
// expected-error@+1 {{expression is 'async' but is not marked with 'await'}}
acceptAsyncSendableClosureInheriting { self.f() }
// expected-note@+2 {{calls to instance method 'f()' from outside of its actor context are implicitly asynchronous}}
// expected-error@+1 {{expression is 'async' but is not marked with 'await'}}
acceptAsyncSendableClosure { self.f() }
}
nonisolated init(a3: Void) async {
// expected-note@+2 {{calls to instance method 'f()' from outside of its actor context are implicitly asynchronous}}
// expected-error@+1 {{expression is 'async' but is not marked with 'await'}}
acceptAsyncSendableClosureInheriting { self.f() }
// expected-note@+2 {{calls to instance method 'f()' from outside of its actor context are implicitly asynchronous}}
// expected-error@+1 {{expression is 'async' but is not marked with 'await'}}
acceptAsyncSendableClosure { self.f() }
}
deinit {
// expected-note@+2 {{calls to instance method 'f()' from outside of its actor context are implicitly asynchronous}}
// expected-error@+1 {{expression is 'async' but is not marked with 'await'}}
acceptAsyncSendableClosureInheriting { self.f() }
// expected-note@+2 {{calls to instance method 'f()' from outside of its actor context are implicitly asynchronous}}
// expected-error@+1 {{expression is 'async' but is not marked with 'await'}}
acceptAsyncSendableClosure { self.f() }
// expected-error@+1 {{call to actor-isolated global function 'takeIsolated' in a synchronous nonisolated context}}
takeIsolated(self)
take(self)
}
func f() {}
}
@MainActor
final class MainActorInit: Sendable {
init() {
acceptAsyncSendableClosureInheriting { self.f() }
// expected-note@+2 {{calls to instance method 'f()' from outside of its actor context are implicitly asynchronous}}
// expected-error@+1 {{expression is 'async' but is not marked with 'await'}}
acceptAsyncSendableClosure { self.f() }
}
deinit {
// expected-note@+2 {{calls to instance method 'f()' from outside of its actor context are implicitly asynchronous}}
// expected-error@+1 {{expression is 'async' but is not marked with 'await'}}
acceptAsyncSendableClosureInheriting { self.f() }
// expected-note@+2 {{calls to instance method 'f()' from outside of its actor context are implicitly asynchronous}}
// expected-error@+1 {{expression is 'async' but is not marked with 'await'}}
acceptAsyncSendableClosure { self.f() }
}
func f() {}
}
actor DunkTracker {
private var lebron: Int?
private var curry: Int?
deinit {
// expected-warning@+1 {{actor-isolated property 'curry' can not be referenced from a non-isolated autoclosure; this is an error in Swift 6}}
if lebron != nil || curry != nil {
}
}
}
| 39.171593 | 237 | 0.675195 |
d592a5adb05075d1a3481fae87fc9a844bf2f50f | 1,888 | /// Copyright (c) 2018 Razeware LLC
///
/// Permission is hereby granted, free of charge, to any person obtaining a copy
/// of this software and associated documentation files (the "Software"), to deal
/// in the Software without restriction, including without limitation the rights
/// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
/// copies of the Software, and to permit persons to whom the Software is
/// furnished to do so, subject to the following conditions:
///
/// The above copyright notice and this permission notice shall be included in
/// all copies or substantial portions of the Software.
///
/// Notwithstanding the foregoing, you may not use, copy, modify, merge, publish,
/// distribute, sublicense, create a derivative work, and/or sell copies of the
/// Software in any work that is designed, intended, or marketed for pedagogical or
/// instructional purposes related to programming, coding, application development,
/// or information technology. Permission for such use, copying, modification,
/// merger, publication, distribution, sublicensing, creation of derivative works,
/// or sale is expressly withheld.
///
/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
/// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
/// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
/// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
/// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
/// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
/// THE SOFTWARE.
import Foundation
struct MarvelResponse<T: Codable>: Codable {
let data: MarvelResults<T>
}
struct MarvelResults<T: Codable>: Codable {
let results: [T]
}
struct ImgurResponse<T: Codable>: Codable {
let data: T
}
| 44.952381 | 83 | 0.751589 |
2356cd3588eda3228c0af3890ff1ba1cbf15ef9e | 2,291 | //
// UIKit.swift
// Noti
//
// Created by Wang Wei on 2018/5/11.
//
import UIKit
public struct UIAccessibilityAnnouncementDidFinishNotification: AutoPassiveTypedNotification {
public struct Payload: AutoPassiveNotificationPayload {
//sourcery: key = "UIAccessibilityAnnouncementKeyStringValue"
public let announcement: String
//sourcery: key = "UIAccessibilityAnnouncementKeyWasSuccessful"
//sourcery: type = "NSNumber"
public let wasSuccessful: Bool
}
}
public struct UIAccessibilityElementFocusedNotification: AutoPassiveTypedNotification {
public struct Payload: AutoPassiveNotificationPayload {
//sourcery: key = "UIAccessibilityFocusedElementKey"
public let element: Any
}
}
public struct UIKeyboardNotificationPayload: AutoPassiveNotificationPayload {
//sourcery: key = "UIKeyboardAnimationCurveUserInfoKey"
//sourcery: type = "NSNumber"
public let animationCurve: UIViewAnimationCurve
//sourcery: key = "UIKeyboardAnimationDurationUserInfoKey"
//sourcery: type = "NSNumber"
public let animationDuration: TimeInterval
//sourcery: key = "UIKeyboardIsLocalUserInfoKey"
//sourcery: type = "NSNumber"
public let isLocal: Bool
//sourcery: key = "UIKeyboardFrameBeginUserInfoKey"
//sourcery: type = "NSValue"
public let frameBegin: CGRect
//sourcery: key = "UIKeyboardFrameEndUserInfoKey"
//sourcery: type = "NSValue"
public let frameEnd: CGRect
}
//sourcery: payload = "UIKeyboardNotificationPayload"
public struct UIKeyboardDidChangeFrameNotification: AutoPassiveTypedNotification {}
//sourcery: payload = "UIKeyboardNotificationPayload"
public struct UIKeyboardDidHideNotification: AutoPassiveTypedNotification {}
//sourcery: payload = "UIKeyboardNotificationPayload"
public struct UIKeyboardDidShowNotification: AutoPassiveTypedNotification {}
//sourcery: payload = "UIKeyboardNotificationPayload"
public struct UIKeyboardWillChangeFrameNotification: AutoPassiveTypedNotification {}
//sourcery: payload = "UIKeyboardNotificationPayload"
public struct UIKeyboardWillHideNotification: AutoPassiveTypedNotification {}
//sourcery: payload = "UIKeyboardNotificationPayload"
public struct UIKeyboardWillShowNotification: AutoPassiveTypedNotification {}
| 40.910714 | 94 | 0.780009 |
ffcff3fa75cf883b8e2b21e9a329886b0091c7b6 | 2,281 | //
// InlineAttributedStringLayoutBlockBuilder.swift
// Pods
//
// Created by Jim van Zummeren on 11/06/16.
//
//
import UIKit
class InlineAttributedStringLayoutBlockBuilder : LayoutBlockBuilder<NSMutableAttributedString> {
fileprivate let converter : MarkDownConverter<NSMutableAttributedString>
required init(converter : MarkDownConverter<NSMutableAttributedString>) {
self.converter = converter
super.init()
}
func attributedStringForMarkDownItem(_ markdownItem : MarkDownItem, styling : ItemStyling) -> NSMutableAttributedString {
let string = NSMutableAttributedString()
if let markDownItems = markdownItem.markDownItems {
for subString in converter.convertToElements(markDownItems, applicableStyling: styling) {
string.append(subString)
}
}
return string
}
func attributedStringWithContentInset(_ attributedString:NSMutableAttributedString, contentInset: UIEdgeInsets) -> NSMutableAttributedString {
// Get existing paragraph style to append style to or create new style
let paragraphStyle = getParagraphStyleAttribute(of: attributedString, exactlyAt: attributedString.fullRange()) ?? NSMutableParagraphStyle()
paragraphStyle.paragraphSpacing = contentInset.bottom
paragraphStyle.paragraphSpacingBefore = contentInset.top
paragraphStyle.firstLineHeadIndent = contentInset.left
paragraphStyle.headIndent = contentInset.left
attributedString.addAttributes([
.paragraphStyle : paragraphStyle
], range: attributedString.fullRange())
return attributedString
}
private func getParagraphStyleAttribute(of attributedString: NSAttributedString, exactlyAt range: NSRange) -> NSMutableParagraphStyle? {
var paragraphStyles: [NSMutableParagraphStyle] = []
attributedString.enumerateAttribute(.paragraphStyle, in: attributedString.fullRange(), options: []) {
value, rangeOfValue, stop in
if let paragraphStyle = value as? NSMutableParagraphStyle, rangeOfValue == range {
paragraphStyles.append(paragraphStyle)
}
}
return paragraphStyles.first
}
}
| 38.016667 | 147 | 0.708461 |
1c7c108b4edbf108a488614f6e2e7762bb7ec9bd | 4,176 | //
// GameService.swift
// GameOn
//
// Created by Andika on 07/08/21.
//
import Foundation
class GameService {
var page = 1
private func fetch(url: URL, completion: @escaping (Result<GamesResponse, Error>) -> Void) {
let config = URLSessionConfiguration.default
config.waitsForConnectivity = true
config.timeoutIntervalForRequest = 10
let urlSession = URLSession(configuration: config)
let task = urlSession.dataTask(with: url) { data, response, _ in
guard let response = response as? HTTPURLResponse else { return }
let statusCode = response.statusCode
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd"
if let data = data {
if statusCode == 200 {
let decoder = JSONDecoder()
decoder.dateDecodingStrategy = .formatted(formatter)
do {
let games = try decoder.decode(GamesResponse.self, from: data)
completion(.success(games))
} catch {
completion(.failure(
DataError.decodingFail(code: -5,
message: "Failure when attempting to decode the data.")
))
}
} else if statusCode >= 300 && statusCode < 400 {
completion(.failure(HttpError.redirection(code: statusCode, message: response.description)))
} else if statusCode < 500 {
completion(.failure(HttpError.clientError(code: statusCode, message: response.description)))
} else if statusCode > 500 && statusCode < 600 {
completion(.failure(HttpError.serverError(code: statusCode, message: response.description)))
} else {
completion(.failure(HttpError.custom(code: statusCode, message: "Unknown status code.")))
}
} else {
completion(.failure(DataError.custom(code: -1, message: "Unknown error, the data is nil.")))
}
}
task.resume()
}
func newRelease(completion: @escaping (Result<GamesResponse, Error>) -> Void) {
fetch(url: GameRepo().getNewlyReleased(page: page)) { status in
switch status {
case .success(let games):
completion(.success(games))
case .failure(let error):
completion(.failure(error))
}
}
}
func topRated(completion: @escaping (Result<GamesResponse, Error>) -> Void) {
fetch(url: GameRepo().getTopRated(page: page)) { status in
switch status {
case .success(let games):
completion(.success(games))
case .failure(let error):
completion(.failure(error))
}
}
}
func platform(platform: Int, completion: @escaping (Result<GamesResponse, Error>) -> Void) {
fetch(url: GameRepo().getPlatformBased(platform: platform)) { status in
switch status {
case .success(let games):
completion(.success(games))
case .failure(let error):
completion(.failure(error))
}
}
}
func discover(completion: @escaping (Result<GamesResponse, Error>) -> Void) {
fetch(url: GameRepo().getDiscovery(page: page)) { status in
switch status {
case .success(let games):
completion(.success(games))
case .failure(let error):
completion(.failure(error))
}
}
}
func search(query: String, completion: @escaping (Result<GamesResponse, Error>) -> Void) {
fetch(url: GameRepo().getSearchQuery(query: query, page: page)) { status in
switch status {
case .success(let games):
completion(.success(games))
case .failure(let error):
completion(.failure(error))
}
}
}
}
| 36.313043 | 114 | 0.535201 |
76d001238bdc77b73bdf48d3f413593d244168da | 2,475 | // Copyright (c) 2018-2021 Brian Dewey. Covered by the Apache 2.0 license.
import Foundation
// From https://oleb.net/blog/2018/03/temp-file-helper/
// A wrapper around a temporary file in a temporary directory. The directory
/// has been especially created for the file, so it's safe to delete when you're
/// done working with the file.
///
/// Call `deleteDirectory` when you no longer need the file.
struct TemporaryFile {
let directoryURL: URL
let fileURL: URL
/// Deletes the temporary directory and all files in it.
let deleteDirectory: () throws -> Void
/// Creates a temporary directory with a unique name and initializes the
/// receiver with a `fileURL` representing a file named `filename` in that
/// directory.
///
/// - Note: This doesn't create the file!
init(creatingTempDirectoryForFilename filename: String) throws {
let (directory, deleteDirectory) = try FileManager.default
.urlForUniqueTemporaryDirectory()
self.directoryURL = directory
self.fileURL = directory.appendingPathComponent(filename)
self.deleteDirectory = deleteDirectory
}
}
extension FileManager {
/// Creates a temporary directory with a unique name and returns its URL.
///
/// - Returns: A tuple of the directory's URL and a delete function.
/// Call the function to delete the directory after you're done with it.
///
/// - Note: You should not rely on the existence of the temporary directory
/// after the app is exited.
func urlForUniqueTemporaryDirectory(
preferredName: String? = nil
) throws -> (url: URL, deleteDirectory: () throws -> Void) {
let basename = preferredName ?? UUID().uuidString
var counter = 0
var createdSubdirectory: URL?
repeat {
do {
let subdirName = counter == 0 ? basename : "\(basename)-\(counter)"
let subdirectory = temporaryDirectory
.appendingPathComponent(subdirName, isDirectory: true)
try createDirectory(at: subdirectory, withIntermediateDirectories: false)
createdSubdirectory = subdirectory
} catch CocoaError.fileWriteFileExists {
// Catch file exists error and try again with another name.
// Other errors propagate to the caller.
counter += 1
}
} while createdSubdirectory == nil
let directory = createdSubdirectory!
let deleteDirectory: () throws -> Void = {
try self.removeItem(at: directory)
}
return (directory, deleteDirectory)
}
}
| 36.397059 | 81 | 0.697778 |
911fc85a9e3f578d5d342920c10e87a5c87e38bf | 13,090 | //
// DetailTourView.swift
// AudioTour
//
// Created by Максим Сурков on 27.03.2021.
//
import Foundation
import UIKit
import Cosmos
import TinyConstraints
class DetailTourView: AutoLayoutView {
var didTapContinue: () -> Void
let scrollableStackView: ScrollableStackView = {
let config: ScrollableStackView.Config = ScrollableStackView.Config(
stack: ScrollableStackView.Config.Stack(axis: .vertical, distribution: .fill,
alignment: .fill, spacing: 0),
scroll: .defaultVertical,
pinsStackConstraints: UIEdgeInsets(top: 0, left: 0, bottom: 0.0, right: 0)
)
return ScrollableStackView(config: config)
}()
//let closure : () -> ()
let collectionView: UICollectionView = {
let layout = UICollectionViewFlowLayout()
layout.sectionInset = UIEdgeInsets(top: 8, left: 8, bottom: 8, right: 8)
layout.scrollDirection = .horizontal
let cv = UICollectionView(frame: .zero, collectionViewLayout: layout)
cv.translatesAutoresizingMaskIntoConstraints = false
cv.register(UICollectionViewCell.self, forCellWithReuseIdentifier: "cell")
cv.backgroundColor = .white
return cv
}()
var viewModel: DetailViewModel?
private let ratingStack = UIStackView()
var starImageViewsArray: [UIImageView] = []
let separateView1 = UIView()
let separateView2 = UIView()
let separateView3 = UIView()
let rateView = UIView()
let descriptionView = UITextView()
let letPathView = UIView()
let letPathButton = UIButton(type: .system)
let organizationView = UIView()
//rateView
let nameLabel = UILabel()
let categoryImage = UIImage()
let categoryImageView = UIImageView()
//let rating = UILabel()
//organizationView
let logoImageView = UIImageView()
var logoImage = UIImage(systemName: "person.3")
var organizationNameLabel = UILabel()
var priceLabel = UILabel()
init(handleContinue: @escaping () -> Void) {
didTapContinue = handleContinue
super.init(frame: .zero)
setup()
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
private func setup() {
addSubview(scrollableStackView)
collectionView.delegate = self
collectionView.dataSource = self
collectionView.register(DetailTourViewCell.self, forCellWithReuseIdentifier: DetailTourViewCell.identifier)
setupSeparatesViews()
scrollableStackView.addArrangedSubview(collectionView)
scrollableStackView.addArrangedSubview(separateView1)
setupNameLabel()
setupRatingView()
rateView.backgroundColor = .white
rateView.heightAnchor.constraint(equalToConstant: 80).isActive = true
scrollableStackView.addArrangedSubview(rateView)
setupTextView()
descriptionView.backgroundColor = .white
descriptionView.isScrollEnabled = false
scrollableStackView.addArrangedSubview(descriptionView)
scrollableStackView.addArrangedSubview(separateView2)
setupTextViewConstraint()
setupOrganizationView()
organizationView.backgroundColor = .white
organizationView.heightAnchor.constraint(equalToConstant: 200).isActive = true
scrollableStackView.addArrangedSubview(organizationView)
scrollableStackView.addArrangedSubview(separateView3)
addSubview(letPathView)
letPathView.addSubview(letPathButton)
}
override func setupConstraints() {
super.setupConstraints()
letPathButton.translatesAutoresizingMaskIntoConstraints = false
letPathView.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
letPathView.bottomAnchor.constraint(equalTo: safeAreaLayoutGuide.bottomAnchor),
letPathView.leadingAnchor.constraint(equalTo: leadingAnchor),
letPathView.trailingAnchor.constraint(equalTo: trailingAnchor)
])
NSLayoutConstraint.activate([
letPathButton.bottomAnchor.constraint(equalTo: letPathView.bottomAnchor, constant: -8),
letPathButton.topAnchor.constraint(equalTo: letPathView.topAnchor, constant: 8),
letPathButton.leadingAnchor.constraint(equalTo: letPathView.leadingAnchor, constant: 50),
letPathButton.trailingAnchor.constraint(equalTo: letPathView.trailingAnchor, constant: -50)
])
NSLayoutConstraint.activate([
scrollableStackView.topAnchor.constraint(equalTo: safeAreaLayoutGuide.topAnchor),
scrollableStackView.leadingAnchor.constraint(equalTo: leadingAnchor),
scrollableStackView.trailingAnchor.constraint(equalTo: trailingAnchor),
scrollableStackView.bottomAnchor.constraint(equalTo: letPathView.topAnchor)
])
NSLayoutConstraint.activate([
collectionView.leadingAnchor.constraint(equalTo: leadingAnchor),
collectionView.trailingAnchor.constraint(equalTo: trailingAnchor),
collectionView.heightAnchor.constraint(equalTo: scrollableStackView.heightAnchor, multiplier: 0.3)
])
setupSeparateViewConstraint()
setupConstraintRatingView()
setupOrganizationViewConstraint()
}
func setupNameLabel() {
self.letPathButton.setTitle("В путь", for: .normal)
self.letPathButton.titleLabel?.font = UIFont(name: "AppleSDGothicNeo-Bold", size: 22)
self.letPathButton.backgroundColor = UIColor.rgba(0, 122, 255)
self.letPathButton.setTitleColor(.white, for: .normal)
self.letPathButton.layer.cornerRadius = 15.0
self.letPathButton.clipsToBounds = false
self.letPathButton.addTarget(self, action: #selector(onTapLetPath), for: .touchUpInside)
}
func setupOrganizationView() {
organizationView.addSubview(logoImageView)
organizationView.addSubview(organizationNameLabel)
organizationView.addSubview(priceLabel)
organizationView.addSubview(ratingStack)
logoImageView.image = logoImage
logoImageView.contentMode = .scaleAspectFit
logoImageView.layer.cornerRadius = 10
logoImageView.clipsToBounds = true
priceLabel.text = "Бесплатно"
organizationNameLabel.text = "Организация: SUKA BLYAT"
organizationNameLabel.font = UIFont(name: "AppleSDGothicNeo-Bold", size: 20)
organizationNameLabel.textColor = .black
}
func setupSeparatesViews() {
separateView1.backgroundColor = .systemGray6
separateView2.backgroundColor = .systemGray6
separateView3.backgroundColor = .systemGray6
}
func setupOrganizationViewConstraint() {
logoImageView.translatesAutoresizingMaskIntoConstraints = false
organizationNameLabel.translatesAutoresizingMaskIntoConstraints = false
priceLabel.translatesAutoresizingMaskIntoConstraints = false
ratingStack.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
logoImageView.leadingAnchor.constraint(equalTo: organizationView.leadingAnchor, constant: 16),
logoImageView.topAnchor.constraint(equalTo: organizationView.topAnchor, constant: 16),
logoImageView.heightAnchor.constraint(equalToConstant: 50),
logoImageView.widthAnchor.constraint(equalTo: logoImageView.heightAnchor),
organizationNameLabel.topAnchor.constraint(equalTo: logoImageView.bottomAnchor, constant: 12),
organizationNameLabel.leadingAnchor.constraint(equalTo: logoImageView.leadingAnchor),
ratingStack.topAnchor.constraint(equalTo: logoImageView.centerYAnchor),
ratingStack.leadingAnchor.constraint(equalTo: logoImageView.trailingAnchor, constant: 8),
priceLabel.topAnchor.constraint(equalTo: ratingStack.topAnchor),
priceLabel.trailingAnchor.constraint(equalTo: organizationView.trailingAnchor, constant: -16),
])
priceLabel.setContentCompressionResistancePriority(UILayoutPriority.defaultHigh, for: .horizontal)
}
func setupSeparateViewConstraint(){
separateView1.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
separateView1.widthAnchor.constraint(equalTo: collectionView.widthAnchor),
separateView1.heightAnchor.constraint(equalToConstant: 12),
separateView2.widthAnchor.constraint(equalTo: collectionView.widthAnchor),
separateView2.heightAnchor.constraint(equalToConstant: 12),
separateView3.widthAnchor.constraint(equalTo: collectionView.widthAnchor),
separateView3.heightAnchor.constraint(equalToConstant: 12)
])
}
func setupRatingView() {
rateView.addSubview(nameLabel)
//rateView.addSubview(rating)
rateView.addSubview(categoryImageView)
ratingStack.axis = .horizontal
ratingStack.distribution = .fillEqually
for _ in 0..<5 {
let imageView = UIImageView(image: UIImage(systemName: "star"))
ratingStack.addArrangedSubview(imageView)
imageView.tintColor = .systemYellow
starImageViewsArray.append(imageView)
}
self.nameLabel.text = "Мурманск"
self.nameLabel.font = UIFont(name: "AppleSDGothicNeo-Bold", size: 22)
self.nameLabel.textColor = .black
nameLabel.lineBreakMode = .byWordWrapping
nameLabel.numberOfLines = 2
// rating.text = " Рейтинг: \(123123)"
// rating.font = UIFont(name: "AppleSDGothicNeo-Thin", size: 18)
categoryImageView.image = UIImage(systemName: "figure.walk")
categoryImageView.contentMode = .scaleAspectFit
}
func setupTextView() {
descriptionView.text = "BKAHSDBHJASBDKJHABSDKHJASBDasdbhahsjdabsdasdnasldnfsdlfnlsakjdfnksadfnljk"
descriptionView.font = UIFont(name: "AppleSDGothicNeo-Light", size: 14)
descriptionView.isEditable = false
}
func setupTextViewConstraint() {
descriptionView.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
descriptionView.leadingAnchor.constraint(equalTo: scrollableStackView.leadingAnchor, constant: 30),
descriptionView.trailingAnchor.constraint(equalTo: scrollableStackView.trailingAnchor, constant: -30)
])
}
func setupConstraintRatingView() {
nameLabel.translatesAutoresizingMaskIntoConstraints = false
ratingStack.translatesAutoresizingMaskIntoConstraints = false
categoryImageView.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
nameLabel.leadingAnchor.constraint(equalTo: rateView.leadingAnchor, constant: 20),
nameLabel.trailingAnchor.constraint(lessThanOrEqualTo: categoryImageView.leadingAnchor, constant: -10),
nameLabel.topAnchor.constraint(equalTo: rateView.topAnchor, constant: 20),
categoryImageView.trailingAnchor.constraint(equalTo: rateView.trailingAnchor, constant: -20),
categoryImageView.topAnchor.constraint(equalTo: rateView.topAnchor, constant: 20),
categoryImageView.heightAnchor.constraint(equalToConstant: 40),
categoryImageView.widthAnchor.constraint(equalTo: categoryImageView.heightAnchor)
])
}
@objc func onTapLetPath() {
didTapContinue()
}
func updateViewModel(viewModel: DetailViewModel) {
self.viewModel = viewModel
collectionView.reloadData()
}
}
extension DetailTourView: UICollectionViewDelegate {
func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1
}
}
extension DetailTourView: UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
viewModel?.images.count ?? 0
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
guard let cell = collectionView.dequeueReusableCell(
withReuseIdentifier: DetailTourViewCell.identifier,
for: indexPath) as? DetailTourViewCell else { fatalError("unexpected collectionViewCell") }
cell.update(with: viewModel?.images[indexPath.item])
cell.layer.cornerRadius = 8
return cell
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
return CGSize(width: collectionView.frame.height / 2, height: collectionView.frame.height - 30)
}
}
| 43.059211 | 160 | 0.697632 |
211ff0b5218c7d8c5a81408296a8591ab9dd5266 | 970 | //
// ClappedByTableViewCell.swift
// CommonFunctionalityFramework
//
// Created by Rewardz on 11/03/20.
// Copyright © 2020 Rewardz. All rights reserved.
//
import UIKit
class ClappedByTableViewCell: UITableViewCell, FeedsCustomCellProtcol {
@IBOutlet weak var containerView : UIView?
@IBOutlet var clappedByUsers : [UIImageView]?
@IBOutlet weak var seeAllButton : BlockButton?
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
class ClappedByTableViewCellType : FeedCellTypeProtocol{
var cellIdentifier: String{
return "ClappedByTableViewCell"
}
var cellNib: UINib?{
return UINib(nibName: "ClappedByTableViewCell", bundle: Bundle(for: FeedTopTableViewCell.self))
}
}
| 25.526316 | 103 | 0.697938 |
726775ac8acd8ee7b873678ba1570349b34accfc | 427 | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
import Foundation
// ConnectionSharedKeyProtocol is response for GetConnectionSharedKey API service call
public protocol ConnectionSharedKeyProtocol : Codable {
var value: String { get set }
}
| 42.7 | 96 | 0.770492 |
fe171a17d563a8a2ba2ef419175379524ca6ec92 | 165 | import XCTest
#if !canImport(ObjectiveC)
public func allTests() -> [XCTestCaseEntry] {
return [
testCase(KJTipCalculatorTests.allTests),
]
}
#endif
| 16.5 | 48 | 0.684848 |
de47949cddef1dfec8d1650932c805ef7797fe94 | 12,638 | //
// FocusEntity.swift
//
//
// Created by Max Cobb on 8/26/19.
//
import RealityKit
import ARKit
import SmartHitTest
private extension UIView {
/// Center of the view
var screenCenter: CGPoint {
let bounds = self.bounds
return CGPoint(x: bounds.midX, y: bounds.midY)
}
}
/**
An `SCNNode` which is used to provide uses with visual cues about the status of ARKit world tracking.
- Tag: FocusSquare
*/
open class FocusEntity: Entity {
weak public var viewDelegate: ARSmartHitTest? {
didSet {
guard let view = self.viewDelegate as? (ARView & ARSmartHitTest) else {
print("FocusNode viewDelegate must be an ARSCNView for now")
return
}
view.scene.addAnchor(povNode)
view.scene.addAnchor(rootNode)
}
}
private var povNode = AnchorEntity()
private var rootNode = AnchorEntity()
// MARK: - Types
public enum State: Equatable {
case initializing
case detecting(hitTestResult: ARHitTestResult, camera: ARCamera?)
}
var screenCenter: CGPoint?
// MARK: - Properties
/// The most recent position of the focus square based on the current state.
var lastPosition: SIMD3<Float>? {
switch state {
case .initializing: return nil
case .detecting(let hitTestResult, _): return hitTestResult.worldTransform.translation
}
}
fileprivate func nodeOffPlane(_ hitTestResult: ARHitTestResult, _ camera: ARCamera?) {
self.onPlane = false
displayOffPlane(for: hitTestResult, camera: camera)
}
public var state: State = .initializing {
didSet {
guard state != oldValue else { return }
switch state {
case .initializing:
if oldValue != .initializing {
displayAsBillboard()
}
case let .detecting(hitTestResult, camera):
if oldValue == .initializing {
self.rootNode.addChild(self)
}
if let planeAnchor = hitTestResult.anchor as? ARPlaneAnchor {
nodeOnPlane(for: hitTestResult, planeAnchor: planeAnchor, camera: camera)
currentPlaneAnchor = planeAnchor
} else {
nodeOffPlane(hitTestResult, camera)
currentPlaneAnchor = nil
}
}
}
}
public var onPlane: Bool = false
/// Indicates if the square is currently being animated.
public var isAnimating = false
/// Indicates if the square is currently changing its alignment.
private var isChangingAlignment = false
/// The focus square's current alignment.
private var currentAlignment: ARPlaneAnchor.Alignment?
/// The current plane anchor if the focus square is on a plane.
private(set) var currentPlaneAnchor: ARPlaneAnchor?
/// The focus square's most recent positions.
private var recentFocusNodePositions: [SIMD3<Float>] = []
/// The focus square's most recent alignments.
private(set) var recentFocusNodeAlignments: [ARPlaneAnchor.Alignment] = []
/// Previously visited plane anchors.
private var anchorsOfVisitedPlanes: Set<ARAnchor> = []
/// The primary node that controls the position of other `FocusEntity` nodes.
public let positioningNode = Entity()
public var scaleNodeBasedOnDistance = true {
didSet {
if self.scaleNodeBasedOnDistance == false {
self.scale = .one
}
}
}
// MARK: - Initialization
public required init() {
super.init()
self.name = "FocusEntity"
self.orientation = simd_quatf(angle: .pi / 2, axis: [1, 0, 0])
// Always render focus square on top of other content.
// self.displayNodeHierarchyOnTop(true)
self.addChild(self.positioningNode)
// Start the focus square as a billboard.
self.displayAsBillboard()
}
required public init?(coder aDecoder: NSCoder) {
fatalError("\(#function) has not been implemented")
}
// MARK: - Appearance
/// Hides the focus square.
public func hide() {
// guard action(forKey: "hide") == nil else { return }
//
// displayNodeHierarchyOnTop(false)
// runAction(.fadeOut(duration: 0.5), forKey: "hide")
}
/// Unhides the focus square.
public func unhide() {
// guard action(forKey: "unhide") == nil else { return }
//
// displayNodeHierarchyOnTop(true)
// runAction(.fadeIn(duration: 0.5), forKey: "unhide")
}
/// Displays the focus square parallel to the camera plane.
private func displayAsBillboard() {
self.povNode.addChild(self)
self.onPlane = false
self.transform = .identity
self.orientation = simd_quatf(angle: .pi / 2, axis: [1, 0, 0])
position = [0, 0, -0.8]
unhide()
stateChangedSetup()
}
/// Called when a surface has been detected.
private func displayOffPlane(for hitTestResult: ARHitTestResult, camera: ARCamera?) {
self.stateChangedSetup()
let position = hitTestResult.worldTransform.translation
recentFocusNodePositions.append(position)
updateTransform(for: position, hitTestResult: hitTestResult, camera: camera)
}
/// Called when a plane has been detected.
private func nodeOnPlane(for hitTestResult: ARHitTestResult, planeAnchor: ARPlaneAnchor, camera: ARCamera?) {
self.onPlane = true
self.stateChangedSetup(newPlane: !anchorsOfVisitedPlanes.contains(planeAnchor))
anchorsOfVisitedPlanes.insert(planeAnchor)
let position = hitTestResult.worldTransform.translation
recentFocusNodePositions.append(position)
updateTransform(for: position, hitTestResult: hitTestResult, camera: camera)
}
// MARK: Helper Methods
/// Update the transform of the focus square to be aligned with the camera.
private func updateTransform(for position: SIMD3<Float>, hitTestResult: ARHitTestResult, camera: ARCamera?) {
// Average using several most recent positions.
recentFocusNodePositions = Array(recentFocusNodePositions.suffix(10))
// Move to average of recent positions to avoid jitter.
let average = recentFocusNodePositions.reduce(
SIMD3<Float>(repeating: 0), { $0 + $1 }
) / Float(recentFocusNodePositions.count)
self.position = average
if self.scaleNodeBasedOnDistance {
self.scale = SIMD3<Float>(repeating: scaleBasedOnDistance(camera: camera))
}
// Correct y rotation of camera square.
guard let camera = camera else { return }
let tilt = abs(camera.eulerAngles.x)
let threshold1: Float = .pi / 2 * 0.65
let threshold2: Float = .pi / 2 * 0.75
let yaw = atan2f(camera.transform.columns.0.x, camera.transform.columns.1.x)
var angle: Float = 0
switch tilt {
case 0..<threshold1:
angle = camera.eulerAngles.y
case threshold1..<threshold2:
let relativeInRange = abs((tilt - threshold1) / (threshold2 - threshold1))
let normalizedY = normalize(camera.eulerAngles.y, forMinimalRotationTo: yaw)
angle = normalizedY * (1 - relativeInRange) + yaw * relativeInRange
default:
angle = yaw
}
if state != .initializing {
updateAlignment(for: hitTestResult, yRotationAngle: angle)
}
}
private func updateAlignment(for hitTestResult: ARHitTestResult, yRotationAngle angle: Float) {
// Abort if an animation is currently in progress.
if isChangingAlignment {
return
}
var shouldAnimateAlignmentChange = false
let tempNode = SCNNode()
tempNode.simdRotation = SIMD4<Float>(0, 1, 0, angle)
// Determine current alignment
var alignment: ARPlaneAnchor.Alignment?
if let planeAnchor = hitTestResult.anchor as? ARPlaneAnchor {
alignment = planeAnchor.alignment
} else if hitTestResult.type == .estimatedHorizontalPlane {
alignment = .horizontal
} else if hitTestResult.type == .estimatedVerticalPlane {
alignment = .vertical
}
// add to list of recent alignments
if alignment != nil {
self.recentFocusNodeAlignments.append(alignment!)
}
// Average using several most recent alignments.
self.recentFocusNodeAlignments = Array(self.recentFocusNodeAlignments.suffix(20))
let horizontalHistory = recentFocusNodeAlignments.filter({ $0 == .horizontal }).count
let verticalHistory = recentFocusNodeAlignments.filter({ $0 == .vertical }).count
// Alignment is same as most of the history - change it
if alignment == .horizontal && horizontalHistory > 15 ||
alignment == .vertical && verticalHistory > 10 ||
hitTestResult.anchor is ARPlaneAnchor {
if alignment != self.currentAlignment {
shouldAnimateAlignmentChange = true
self.currentAlignment = alignment
self.recentFocusNodeAlignments.removeAll()
}
} else {
// Alignment is different than most of the history - ignore it
alignment = self.currentAlignment
return
}
if alignment == .vertical {
tempNode.simdOrientation = hitTestResult.worldTransform.orientation
shouldAnimateAlignmentChange = true
}
// Change the focus square's alignment
if shouldAnimateAlignmentChange {
performAlignmentAnimation(to: tempNode.simdOrientation)
} else {
orientation = tempNode.simdOrientation
}
}
private func normalize(_ angle: Float, forMinimalRotationTo ref: Float) -> Float {
// Normalize angle in steps of 90 degrees such that the rotation to the other angle is minimal
var normalized = angle
while abs(normalized - ref) > .pi / 4 {
if angle > ref {
normalized -= .pi / 2
} else {
normalized += .pi / 2
}
}
return normalized
}
/**
Reduce visual size change with distance by scaling up when close and down when far away.
These adjustments result in a scale of 1.0x for a distance of 0.7 m or less
(estimated distance when looking at a table), and a scale of 1.2x
for a distance 1.5 m distance (estimated distance when looking at the floor).
*/
private func scaleBasedOnDistance(camera: ARCamera?) -> Float {
guard let camera = camera else { return 1.0 }
let distanceFromCamera = simd_length(self.convert(position: .zero, to: nil) - camera.transform.translation)
if distanceFromCamera < 0.7 {
return distanceFromCamera / 0.7
} else {
return 0.25 * distanceFromCamera + 0.825
}
}
// MARK: Animations
/// Called whenever the state of the focus node changes
///
/// - Parameter newPlane: If the node is directly on a plane, is it a new plane to track
public func stateChanged(newPlane: Bool = false) {
if self.onPlane {
/// Used when the node is tracking directly on a plane
} else {
/// Used when the node is tracking, but is estimating the plane
}
isAnimating = false
}
private func stateChangedSetup(newPlane: Bool = false) {
guard !isAnimating else { return }
isAnimating = true
self.stateChanged(newPlane: newPlane)
}
/// - TODO: Animate this orientation change
private func performAlignmentAnimation(to newOrientation: simd_quatf) {
orientation = newOrientation
}
/// - TODO: RealityKit to allow for setting render order
/// Sets the rendering order of the `positioningNode` to show on top or under other scene content.
// func displayNodeHierarchyOnTop(_ isOnTop: Bool) {
// // Recursivley traverses the node's children to update the rendering order depending on the `isOnTop` parameter.
// func updateRenderOrder(for node: Entity) {
// node.render = isOnTop ? 2 : 0
//
// for material in node.geometry?.materials ?? [] {
// material.readsFromDepthBuffer = !isOnTop
// }
//
// for child in node.childNodes {
// updateRenderOrder(for: child)
// }
// }
// updateRenderOrder(for: self.positioningNode)
// }
public func updateFocusNode() {
guard let view = self.viewDelegate as? (ARView & ARSmartHitTest) else {
print("FocusNode viewDelegate must be an ARSCNView for now")
return
}
// Perform hit testing only when ARKit tracking is in a good state.
guard let camera = session.currentFrame?.camera,
case .normal = camera.trackingState
else {
self.state = .initializing
povNode.transform = view.cameraTransform
return
}
var result: ARHitTestResult?
if !Thread.isMainThread {
if let center = self.screenCenter {
result = view.smartHitTest(center)
} else {
DispatchQueue.main.async {
self.screenCenter = view.screenCenter
self.updateFocusNode()
}
return
}
} else {
result = view.smartHitTest(view.screenCenter)
}
if let result = result {
self.state = .detecting(hitTestResult: result, camera: camera)
} else {
povNode.transform = view.cameraTransform
self.state = .initializing
}
}
}
| 31.595 | 118 | 0.681912 |
ff2475d6450153e3ae17c4f68eda4e4c77491722 | 4,707 | //
// ProcessController.swift
// App
//
// Created by 晋先森 on 2018/7/20.
//
import Foundation
import Vapor
// Swift 与 Python 交互。
class ProcessController: RouteCollection {
func boot(router: Router) throws {
router.group("process") { (group) in
group.get("screenshot", use: uploadLeafHandler)
group.post(ConvertImage.self, at: "convertImage", use: convertImagesUsePythonHandler)
group.get("sum", use: sumTestHandler)
}
}
}
extension ProcessController {
func sumTestHandler(_ req: Request) throws -> Future<String> {
let promise = req.eventLoop.newPromise(String.self)
let a = req.query[String.self,at: "a"] ?? "0"
let b = req.query[String.self,at: "b"] ?? "0"
let task = Process()
task.launchPath = VaporUtils.python3Path()
task.arguments = ["sum.py",a,b]
let outPipe = Pipe()
let errPipe = Pipe()
task.standardOutput = outPipe
task.standardError = errPipe
let pyFileDir = DirectoryConfig.detect().workDir + "Public/py"
task.currentDirectoryPath = pyFileDir + "/demo"
task.terminationHandler = { proce in
let data = outPipe.fileHandleForReading.readDataToEndOfFile()
let result = String(data: data, encoding: .utf8) ?? ""
promise.succeed(result: result)
}
task.launch()
task.waitUntilExit()
return promise.futureResult
}
func uploadLeafHandler(_ req: Request) throws -> Future<View> {
return try req.view().render("process/screenshot")
}
private func convertImagesUsePythonHandler(_ req: Request,container: ConvertImage) throws -> Future<Response> {
let promise = req.eventLoop.newPromise(Response.self)
let pyFileDir = DirectoryConfig.detect().workDir + "Public/py"
let inputPath = pyFileDir + "/convert/input"
let manager = FileManager.default
if !manager.fileExists(atPath: inputPath) { //不存在则创建
try manager.createDirectory(atPath: inputPath,
withIntermediateDirectories: true, attributes: nil)
}
var imgPath: String?
if let file = container.img {
guard file.data.count < ImageMaxByteSize else {
return try ResponseJSON<Empty>(status: .pictureTooBig).encode(for: req)
}
let imgName = try VaporUtils.randomString() + ".png"
imgPath = inputPath + "/" + imgName
try Data(file.data).write(to: URL(fileURLWithPath: imgPath!))
}
var bgPath: String?
if let file = container.bg {
guard file.data.count < ImageMaxByteSize else {
return try ResponseJSON<Empty>(status: .pictureTooBig).encode(for: req)
}
let bgName = try VaporUtils.randomString() + ".png"
bgPath = inputPath + "/" + bgName
try Data(file.data).write(to: URL(fileURLWithPath: bgPath!))
}
let arcName = try VaporUtils.randomString()
let task = Process()
task.launchPath = VaporUtils.python3Path()
task.arguments = ["toImage.py",arcName,container.d ?? "1",imgPath ?? "",bgPath ?? ""]
task.currentDirectoryPath = pyFileDir + "/convert"
task.terminationHandler = { proce in
let filePath = pyFileDir + "/convert/out/\(arcName).jpg"
if let data = manager.contents(atPath: filePath) {
let shot = ScreenShot(id: nil,
imgPath: imgPath,
bgPath: bgPath,
outPath: filePath,
desc: req.http.headers.description,
time: TimeManager.current())
shot.save(on: req).whenFailure({ (error) in
print("保存失败 \(error)")
})
_ = shot.save(on: req)
let res = req.makeResponse(data)
promise.succeed(result: res)
}else {
promise.succeed(result: req.makeResponse("必须上传2张图片"))
}
}
task.launch()
task.waitUntilExit()
return promise.futureResult
}
}
private struct ConvertImage: Content {
var d: String?
var img: File?
var bg: File?
}
| 30.967105 | 115 | 0.531124 |
5d070dfce4336595e4f73d02e151da663c595c34 | 7,103 | /*
* Copyright 2020 ZUP IT SERVICOS EM TECNOLOGIA E INOVACAO SA
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import XCTest
@testable import BeagleUI
class CacheDiskManagerTests: XCTestCase {
// swiftlint:disable force_unwrapping
private let jsonData = """
{
"_beagleType_": "beagle:component:text",
"text": "cache",
"appearance": {
"backgroundColor": "#4000FFFF"
}
}
""".data(using: .utf8)!
// swiftlint:enable force_unwrapping
func testGetReference() {
let sut = DefaultCacheDiskManager(dependencies: CacheDiskManagerDependencies())
sut.clear()
let hash = "1"
let identifier = "id"
let reference = CacheReference(identifier: identifier, data: jsonData, hash: hash, timeOfCreation: generateTimeOfCreation())
sut.update(reference)
guard let result = sut.getReference(for: identifier) else {
XCTFail("Could not retrive data.")
return
}
XCTAssert(result.data == jsonData, "Got wrong data from cache.")
XCTAssert(result.hash == hash, "Got wrong data from cache.")
XCTAssert(result.identifier == identifier, "Got wrong data from cache.")
}
func testGetNilRefereence() {
let sut = DefaultCacheDiskManager(dependencies: CacheDiskManagerDependencies())
sut.clear()
sut.saveChanges()
let identifier = "id"
if sut.getReference(for: identifier) != nil {
XCTFail("Should not retrive data.")
}
}
func testClear() {
let sut = DefaultCacheDiskManager(dependencies: CacheDiskManagerDependencies())
let identifier = "id"
let hash = "1"
let reference = CacheReference(identifier: identifier, data: jsonData, hash: hash)
sut.update(reference)
sut.saveChanges()
sut.clear()
if sut.getReference(for: identifier) != nil {
XCTFail("Should not retrive data.")
}
}
func testRemoveLastUsed() {
let sut = DefaultCacheDiskManager(dependencies: CacheDiskManagerDependencies())
let identifier1 = "id1"
let hash1 = "1"
let identifier2 = "id2"
let hash2 = "2"
sut.clear()
let reference1 = CacheReference(identifier: identifier1, data: jsonData, hash: hash1)
let reference2 = CacheReference(identifier: identifier2, data: jsonData, hash: hash2)
sut.update(reference1)
sut.update(reference2)
sut.removeLastUsed()
sut.saveChanges()
if sut.getReference(for: identifier1) != nil {
XCTFail("Should not retrive data.")
}
}
func testRemoveLastUsedUpdated() {
let sut = DefaultCacheDiskManager(dependencies: CacheDiskManagerDependencies())
sut.clear()
let identifier1 = "id1"
let hash1 = "1"
let identifier2 = "id2"
let hash2 = "2"
let hash3 = "3"
sut.clear()
let reference1 = CacheReference(identifier: identifier1, data: jsonData, hash: hash1)
let reference2 = CacheReference(identifier: identifier2, data: jsonData, hash: hash2)
sut.update(reference1)
sut.update(reference2)
let reference3 = CacheReference(identifier: identifier1, data: jsonData, hash: hash3)
sut.update(reference3)
sut.removeLastUsed()
sut.saveChanges()
if sut.getReference(for: identifier2) != nil {
XCTFail("Should not retrive data.")
}
}
func testInsertNewValue() {
let sut = DefaultCacheDiskManager(dependencies: CacheDiskManagerDependencies())
let identifier = "id"
let hash = "1"
let reference = CacheReference(identifier: identifier, data: jsonData, hash: hash, timeOfCreation: generateTimeOfCreation())
sut.update(reference)
guard let result = sut.getReference(for: identifier) else {
XCTFail("Could not retrive data.")
return
}
XCTAssert(result.data == jsonData, "Got wrong data from cache.")
XCTAssert(result.hash == hash, "Got wrong data from cache.")
XCTAssert(result.identifier == identifier, "Got wrong data from cache.")
}
func testUpdateValue() {
let sut = DefaultCacheDiskManager(dependencies: CacheDiskManagerDependencies())
let identifier = "id"
let hash = "1"
let hash2 = "2"
let reference = CacheReference(identifier: identifier, data: jsonData, hash: hash, timeOfCreation: generateTimeOfCreation())
sut.update(reference)
let reference1 = CacheReference(identifier: identifier, data: jsonData, hash: hash2, timeOfCreation: generateTimeOfCreation())
sut.update(reference1)
guard let result = sut.getReference(for: identifier) else {
XCTFail("Could not retrive data.")
return
}
XCTAssert(result.data == jsonData, "Got wrong data from cache.")
XCTAssert(result.hash == hash2, "Got wrong data from cache.")
XCTAssert(result.identifier == identifier, "Got wrong data from cache.")
}
func testNumberOfRegistersNoRegisters() {
let sut = DefaultCacheDiskManager(dependencies: CacheDiskManagerDependencies())
sut.clear()
XCTAssert(sut.numberOfReferences() == 0, "Counted references wrong")
}
func testNumberOfRegistersWithRegisters() {
let sut = DefaultCacheDiskManager(dependencies: CacheDiskManagerDependencies())
let identifier1 = "id1"
let hash1 = "1"
let identifier2 = "id2"
let hash2 = "2"
sut.clear()
let reference1 = CacheReference(identifier: identifier1, data: jsonData, hash: hash1)
let reference2 = CacheReference(identifier: identifier2, data: jsonData, hash: hash2)
sut.update(reference1)
sut.update(reference2)
XCTAssert(sut.numberOfReferences() == 2, "Counted references wrong")
}
private func generateTimeOfCreation() -> Date {
let stringDate = "2020-01-01"
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd"
// swiftlint:disable force_unwrapping
return dateFormatter.date(from: stringDate)!
// swiftlint:enable force_unwrapping
}
}
struct CacheDiskManagerDependencies: DefaultCacheDiskManager.Dependencies {
var logger: BeagleLoggerType = BeagleLogger()
}
| 36.613402 | 134 | 0.635647 |
fb1b19cd340ddd48b259dc2beb6ccbf0a084613a | 7,910 | //
// HomePageViewModel.swift
// RestaurantFinalApp
//
// Created by Gizem Boskan on 8.08.2021.
//
import Foundation
import Firebase
import MapKit
protocol HomePageViewModelProtocol {
var delegate: HomePageViewModelDelegate? { get set }
var myRecipes: [RecipeModel] { get set }
var activeOrder: RecipeModel? { get set }
var kitchens: [KitchenModel] { get set }
func getMyRecipes()
func getUserLocation()
func getKitchens()
}
protocol HomePageViewModelDelegate: AnyObject {
func showAlert(message: String, title: String)
func showLoadingIndicator(isShown: Bool)
func myRecipesLoaded() // signal to view layer to say "I loaded the datas, and you can take an action."
func kitchensLoaded()
func showLocationString(locationString: String)
func showOrderStatus()
}
final class HomePageViewModel: NSObject {
// MARK: - Properties
weak var delegate: HomePageViewModelDelegate?
var myRecipes: [RecipeModel] = []
var activeOrder: RecipeModel?
var kitchens: [KitchenModel] = []
let locationManager = CLLocationManager()
var userLocation: CLLocation?
private var myUserDetail: UserModel?
private lazy var geocoder = CLGeocoder()
override init() {
super.init()
NotificationCenter.default.addObserver(self, selector: #selector(onDidReceiveOrder(_:)), name: .orderActivated, object: nil)
}
@objc func onDidReceiveOrder(_ notification: Notification) {
if let recipe = notification.userInfo?["recipe"] as? RecipeModel {
activeOrder = recipe
delegate?.showOrderStatus()
}
}
// MARK: - Helpers
private func checkLocationServices() {
if CLLocationManager.locationServicesEnabled() {
setupLocationManager()
checkLocationAuthorization()
}
}
private func getUserReverseGeocode(longitude: Double, latitude: Double) {
DispatchQueue.main.async {
self.geocoder.reverseGeocodeLocation(CLLocation(latitude: latitude, longitude: longitude)) { [weak self] (placemarks, error) in
guard let self = self else { return }
if let error = error {
print(error)
return
}
guard let placemark = placemarks?.first else { return }
var locationString = ""
if let thoroughfare = placemark.thoroughfare {
locationString += thoroughfare + ", "
}
if let locality = placemark.locality {
locationString += locality + ", "
}
if let subLocality = placemark.subLocality {
locationString += subLocality + ", "
}
if let subThoroughfare = placemark.subThoroughfare {
locationString += subThoroughfare + ", "
}
if let administrativeArea = placemark.administrativeArea {
locationString += administrativeArea
}
self.delegate?.showLocationString(locationString: locationString)
}
}
}
private func setupLocationManager() {
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyBest
}
private func checkLocationAuthorization() {
switch CLLocationManager.authorizationStatus() {
case .authorizedWhenInUse:
getLocation()
case .denied:
break
case .notDetermined:
locationManager.requestWhenInUseAuthorization()
case .authorizedAlways:
getLocation()
case .restricted:
break
}
}
private func getLocation() {
if (CLLocationManager.authorizationStatus() == CLAuthorizationStatus.authorizedWhenInUse ||
CLLocationManager.authorizationStatus() == CLAuthorizationStatus.authorizedAlways){
guard let userLocation = locationManager.location else {
return
}
print(userLocation.coordinate.latitude)
print(userLocation.coordinate.longitude)
let lat = userLocation.coordinate.latitude
let long = userLocation.coordinate.longitude
getUserReverseGeocode(longitude: long, latitude: lat)
}
}
}
// MARK: - Accessors
extension HomePageViewModel: HomePageViewModelProtocol {
func getMyRecipes() {
delegate?.showLoadingIndicator(isShown: true)
FirebaseEndpoints.myUser.getDatabasePath.child("recipes").getData{ [weak self] (error, snapshot) in
self?.delegate?.showLoadingIndicator(isShown: false)
if let error = error {
self?.delegate?.showAlert(message: "general_error_desc".localized(), title: "general_error_title".localized())
print("Error getting data \(error)")
}
else if snapshot.exists() {
print("Got data \(snapshot.value!)")
var tempRecipes: [RecipeModel] = []
if let myRecipesDict = snapshot.value as? [String: Any] {
for recipe in myRecipesDict {
if let recipeDetails = recipe.value as? [String: Any] {
let myRecipe = RecipeModel.getRecipeFromDict(recipeDetails: recipeDetails)
tempRecipes.append(myRecipe)
}
}
self?.myRecipes.removeAll()
self?.myRecipes = Array(tempRecipes.prefix(5))
}
self?.delegate?.myRecipesLoaded()
}
else {
self?.delegate?.showAlert(message: "general_error_desc".localized(), title: "general_error_title".localized())
print("No data available")
}
}
}
func getUserLocation() {
checkLocationServices()
locationManager.requestWhenInUseAuthorization()
}
func getKitchens() {
delegate?.showLoadingIndicator(isShown: true)
FirebaseEndpoints.kitchens.getDatabasePath.getData{ [weak self] (error, snapshot) in
self?.delegate?.showLoadingIndicator(isShown: false)
if let error = error {
self?.delegate?.showAlert(message: "general_error_desc".localized(), title: "general_error_title".localized())
print("Error getting data \(error)")
}
else if snapshot.exists() {
print("Got data \(snapshot.value!)")
self?.kitchens.removeAll()
if let kitchensDict = snapshot.value as? [String: Any] {
for kitchen in kitchensDict {
if let kitchenDetails = kitchen.value as? [String: Any] {
let kitchen = KitchenModel.getKitchenFromDict(kitchenDetails: kitchenDetails)
self?.kitchens.append(kitchen)
}
}
}
self?.delegate?.kitchensLoaded()
}
else {
self?.delegate?.showAlert(message: "general_error_desc".localized(), title: "general_error_title".localized())
print("No data available")
}
}
}
}
// MARK: - Location Manager Delegate
extension HomePageViewModel: CLLocationManagerDelegate {
func locationManagerDidChangeAuthorization(_ manager: CLLocationManager) {
checkLocationAuthorization()
}
}
| 35.954545 | 139 | 0.571302 |
dbfa96f2a901c3e351a14569f8f402de00dff5c3 | 1,237 | import Vapor
struct BotDictionaries {
let greetingMessageDictonary: BotGreetingMessageDictionary
let conversationDictionary: BotConversationDictionary
let leaveMessageDictionary: BotLeaveMessageDictionary
let badwordDictionary: BotBadwordDictionary
let fallbackDictionary: BotFallbackDictionary
}
extension BotDictionaries {
static func load(for app: Application) throws -> BotDictionaries {
let loader = JSONLoader(directory: app.configuration.paths.dictionary)
let greetingMessage: BotGreetingMessageDictionary = try loader.load(for: app, name: "greeting")
let leave: BotLeaveMessageDictionary = try loader.load(for: app, name: "leave")
let badword: BotBadwordDictionary = try loader.load(for: app, name: "badword")
let fallback: BotFallbackDictionary = try loader.load(for: app, name: "fallback")
let conversation: BotConversationDictionary = try loader.load(for: app, name: "conversation")
return .init(
greetingMessageDictonary: greetingMessage,
conversationDictionary: conversation,
leaveMessageDictionary: leave,
badwordDictionary: badword,
fallbackDictionary: fallback
)
}
}
| 44.178571 | 103 | 0.727567 |
e90df726e156d68ff96a5e76e94aef91ffd0fa77 | 512 | //
// MainViewController.swift
// NovastoneCodeTest
//
// Created by Anderson Gralha on 21/08/20.
// Copyright © 2020 Anderson Gralha. All rights reserved.
//
import UIKit
class MainViewController: UINavigationController {
override func viewDidLoad() {
super.viewDidLoad()
let viewController = UniversityListViewController(nibName: nil, bundle: nil)
addChild(viewController)
view.addSubview(viewController.view)
viewController.didMove(toParent: self)
}
}
| 22.26087 | 84 | 0.705078 |
fb801fd9847754ef97e1ab676c8a759ccea16747 | 317 | public protocol SimpleProto {
func successor() -> Self
}
public protocol ComplexProto : SimpleProto {
func predecessor() -> Self
}
public protocol ProtoUser {
associatedtype Element
associatedtype Impl: SimpleProto
var start: Impl { get }
var end: Impl { get }
subscript(_: Impl) -> Element { get }
}
| 19.8125 | 44 | 0.70347 |
accfc2a5a31d79e18c5cac3f7044e69426aa56ef | 2,402 | //----------------------------------------------------
//
// Generated by www.easywsdl.com
// Version: 5.7.0.0
//
// Created by Quasar Development
//
//---------------------------------------------------
import Foundation
/**
* specDomain: S20239 (C-0-T19465-S20096-S20239-cpt)
*/
public enum EPA_FdV_AUTHZ_PsychiatryandNeurologyProviderCodes:Int,CustomStringConvertible
{
case _208400000X
case _2084A0401X
case _2084P0802X
case _2084P0804X
case _2084N0600X
case _2084F0202X
case _2084P0805X
case _2084P0005X
case _2084N0400X
case _2084N0402X
case _2084P2900X
case _2084P0800X
case _2084S0010X
case _2084V0102X
static func createWithXml(node:DDXMLNode) -> EPA_FdV_AUTHZ_PsychiatryandNeurologyProviderCodes?
{
return createWithString(value: node.stringValue!)
}
static func createWithString(value:String) -> EPA_FdV_AUTHZ_PsychiatryandNeurologyProviderCodes?
{
var i = 0
while let item = EPA_FdV_AUTHZ_PsychiatryandNeurologyProviderCodes(rawValue: i)
{
if String(describing: item) == value
{
return item
}
i += 1
}
return nil
}
public var stringValue : String
{
return description
}
public var description : String
{
switch self
{
case ._208400000X: return "208400000X"
case ._2084A0401X: return "2084A0401X"
case ._2084P0802X: return "2084P0802X"
case ._2084P0804X: return "2084P0804X"
case ._2084N0600X: return "2084N0600X"
case ._2084F0202X: return "2084F0202X"
case ._2084P0805X: return "2084P0805X"
case ._2084P0005X: return "2084P0005X"
case ._2084N0400X: return "2084N0400X"
case ._2084N0402X: return "2084N0402X"
case ._2084P2900X: return "2084P2900X"
case ._2084P0800X: return "2084P0800X"
case ._2084S0010X: return "2084S0010X"
case ._2084V0102X: return "2084V0102X"
}
}
public func getValue() -> Int
{
return rawValue
}
func serialize(__parent:DDXMLNode)
{
__parent.stringValue = stringValue
}
}
| 26.108696 | 101 | 0.56453 |
20017ca5fbd7c8a6b87a131b1bc24055949e7826 | 3,821 | //
// Alignment2Review.swift
// CaucusReport
//
// Created by Darrell Root on 2/9/20.
// Copyright © 2020 net.networkmom. All rights reserved.
//
import SwiftUI
struct Alignment2Review: View {
@EnvironmentObject var model: Model
@State var showingAlert = false
@State var alertTitle = ""
@State var alertMessage = ""
var body: some View {
VStack {
VStack(alignment: .leading) {
Text("Total Align1 Votes=\(model.early1GrandTotal)+\(model.attendee1GrandTotal)=\(model.align1GrandTotal)").padding(.top)
Text("Total Align2 Votes=\(model.early2GrandTotal)+\(model.attendee2GrandTotal)=\(model.align2GrandTotal)")
Text("Total early and attendee registrations \(model.totalRegistrations)")
Text("Delegates \(model.precinctDelegates)")
Text("Viability percentage \(model.viabilityPercentage)")
Text("Votes required for viability \(model.viability)")
Text("Alignment 2 Viable Votes").font(.headline)
}
List(model.viableCandidates, id: \.self) { candidate in
HStack {
Text("\(candidate) \(self.model.earlyVote2[candidate]!)+\(self.model.attendeeVote2[candidate]!)=\(self.model.align2Total(candidate: candidate))")
Spacer()
Text(String(format: "%.4f",self.model.delegateFactor(candidate: candidate)))
//Text("\(self.model.delegateFactor(candidate: candidate))")
}.foregroundColor(self.model.viable2(candidate: candidate) ? Color.blue : Color.red)
}
model.validResult ? Text(model.delegateMessage()) : Text(model.invalidMessage)
model.validResult ? Button(action: { self.tweet() }) {
Text("Tweet alignment 2 results")
} :
Button(action: { }) {
Text("Fix invalid data before tweeting")
}
}.alert(isPresented: $showingAlert) {
Alert(title: Text(alertTitle), message: Text(alertMessage), dismissButton: .default(Text("Ok")))
}.onAppear {
self.model.saveData()
if self.model.align2GrandTotal == 0 {
self.alertTitle = "No votes entered"
self.alertMessage = "If you don't enter any votes, it looks like a 12-way tie!"
self.showingAlert = true
}
if self.model.totalRegistrations == 0 {
self.alertTitle = "No attendees"
self.alertMessage = "It looks like you did not enter # of attendees on Precinct Screen"
self.showingAlert = true
}
}
.navigationBarTitle("Align 2 Review", displayMode: .inline)
/*.navigationBarItems(trailing: NavigationLink(destination: EarlyVoter2View()) {
Text("Align 2 Early Vote")
})*/
}
func tweet() {
if let align2Tweet = model.align2Tweet, let url = URL(string:"twitter://post?message=\(align2Tweet)"), UIApplication.shared.canOpenURL(url) {
UIApplication.shared.open(url, options: [:],
completionHandler: {
(success) in
if success == false {
self.twitterAlert()
}
debugPrint("Open \(url): \(success)")
})
} else {
self.twitterAlert()
}
}
func twitterAlert() {
self.alertTitle = "Unable to open Twitter application"
self.alertMessage = "Make sure Twitter is installed"
self.showingAlert = true
}
}
/*struct Alignment1Review_Previews: PreviewProvider {
static var previews: some View {
Alignment1Review()
}
}*/
| 43.420455 | 165 | 0.570531 |
39018d9c2c992210344d39c8546f4508e2943a7f | 497 | // Copyright (c) 2021 Payoneer Germany GmbH
// https://www.payoneer.com
//
// This file is open source and available under the MIT license.
// See the LICENSE file for more information.
import Foundation
struct ListResultNetworks {
let listResult: ListResult
let filteredNetworks: FilteredNetworks
struct FilteredNetworks {
let applicableNetworks: [ApplicableNetwork]
let accountRegistrations: [AccountRegistration]
let presetAccount: PresetAccount?
}
}
| 26.157895 | 64 | 0.736419 |
acca9bb4f610d7469a67e4e3d3fd6708dd97a8cc | 1,723 | // Copyright 2019 Algorand, Inc.
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// NodeHealthOperation.swift
import Foundation
class NodeHealthOperation: AsyncOperation {
let address: String?
let token: String?
let api: AlgorandAPI
var onStarted: EmptyHandler?
var onCompleted: BoolHandler?
init(node: Node, api: AlgorandAPI) {
self.address = node.address
self.token = node.token
self.api = api
super.init()
}
init(address: String?, token: String?, api: AlgorandAPI) {
self.address = address
self.token = token
self.api = api
super.init()
}
override func main() {
if isCancelled {
return
}
guard let address = self.address,
let token = self.token else {
self.onCompleted?(false)
self.state = .finished
return
}
let nodeTestDraft = NodeTestDraft(address: address, token: token)
api.checkNodeHealth(with: nodeTestDraft) { isHealthy in
self.onCompleted?(isHealthy)
self.state = .finished
}
onStarted?()
}
}
| 26.921875 | 75 | 0.618688 |
d73f3ba73470d4f8321edc7540e464d6a1be9546 | 232 | public class Observable<Element> {
public typealias E = Element
}
Observable.create { }
// RUN: %sourcekitd-test -req=cursor -cursor-action -pos=4:12 -length 10 %s -- %s | %FileCheck %s
// CHECK: source.lang.swift.ref.module ()
| 25.777778 | 97 | 0.689655 |
d9600a5965e11e70e999f350efee377a84608e14 | 1,739 | //
// FaqViewController.swift
// Simple Login
//
// Created by Thanh-Nhon Nguyen on 16/01/2020.
// Copyright © 2020 SimpleLogin. All rights reserved.
//
import UIKit
final class FaqViewController: BaseViewController {
@IBOutlet private weak var tableView: UITableView!
private var faqs: [Faq] = []
override func viewDidLoad() {
super.viewDidLoad()
setUpUI()
readFaqsFromPlist()
}
private func setUpUI() {
tableView.rowHeight = UITableView.automaticDimension
tableView.tableFooterView = UIView(frame: .zero)
tableView.separatorColor = .clear
FaqTableViewCell.register(with: tableView)
}
private func readFaqsFromPlist() {
if let url = Bundle.main.url(forResource: "Faq", withExtension: "plist"), let faqArray = NSArray(contentsOf: url) as? [[String: String]] {
faqArray.forEach { (faqDictionary) in
if let question = faqDictionary["question"], let answer = faqDictionary["answer"] {
let faq = Faq(question: question, answer: answer)
faqs.append(faq)
}
}
}
}
}
// MARK: - FaqViewController
extension FaqViewController: UITableViewDataSource {
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return faqs.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = FaqTableViewCell.dequeueFrom(tableView, forIndexPath: indexPath)
cell.bind(with: faqs[indexPath.row])
return cell
}
}
| 30.508772 | 146 | 0.636573 |
e9424798d3c4f01085c46faa84449f21c52e2a98 | 18,109 | // RUN: %target-typecheck-verify-swift
// REQUIRES: objc_interop
import Foundation
public class BridgedClass : NSObject, NSCopying {
@objc(copyWithZone:)
public func copy(with zone: NSZone?) -> Any {
return self
}
}
public class BridgedClassSub : BridgedClass { }
// Attempt to bridge to a type from another module. We only allow this for a
// few specific types, like String.
extension LazyFilterSequence.Iterator : _ObjectiveCBridgeable { // expected-error{{conformance of 'Iterator' to '_ObjectiveCBridgeable' can only be written in module 'Swift'}}
public typealias _ObjectiveCType = BridgedClassSub
public func _bridgeToObjectiveC() -> _ObjectiveCType {
return BridgedClassSub()
}
public static func _forceBridgeFromObjectiveC(
_ source: _ObjectiveCType,
result: inout LazyFilterSequence.Iterator?
) { }
public static func _conditionallyBridgeFromObjectiveC(
_ source: _ObjectiveCType,
result: inout LazyFilterSequence.Iterator?
) -> Bool {
return true
}
public static func _unconditionallyBridgeFromObjectiveC(_ source: _ObjectiveCType?)
-> LazyFilterSequence.Iterator {
let result: LazyFilterSequence.Iterator?
return result!
}
}
struct BridgedStruct : Hashable, _ObjectiveCBridgeable {
func hash(into hasher: inout Hasher) {}
func _bridgeToObjectiveC() -> BridgedClass {
return BridgedClass()
}
static func _forceBridgeFromObjectiveC(
_ x: BridgedClass,
result: inout BridgedStruct?) {
}
static func _conditionallyBridgeFromObjectiveC(
_ x: BridgedClass,
result: inout BridgedStruct?
) -> Bool {
return true
}
static func _unconditionallyBridgeFromObjectiveC(_ source: BridgedClass?)
-> BridgedStruct {
var result: BridgedStruct?
_forceBridgeFromObjectiveC(source!, result: &result)
return result!
}
}
func ==(x: BridgedStruct, y: BridgedStruct) -> Bool { return true }
struct NotBridgedStruct : Hashable {
func hash(into hasher: inout Hasher) {}
}
func ==(x: NotBridgedStruct, y: NotBridgedStruct) -> Bool { return true }
class OtherClass : Hashable {
func hash(into hasher: inout Hasher) {}
}
func ==(x: OtherClass, y: OtherClass) -> Bool { return true }
// Basic bridging
func bridgeToObjC(_ s: BridgedStruct) -> BridgedClass {
return s // expected-error{{cannot convert return expression of type 'BridgedStruct' to return type 'BridgedClass'}}
return s as BridgedClass
}
func bridgeToAnyObject(_ s: BridgedStruct) -> AnyObject {
return s // expected-error{{return expression of type 'BridgedStruct' expected to be an instance of a class or class-constrained type}}
return s as AnyObject
}
func bridgeFromObjC(_ c: BridgedClass) -> BridgedStruct {
return c // expected-error{{'BridgedClass' is not implicitly convertible to 'BridgedStruct'; did you mean to use 'as' to explicitly convert?}}
return c as BridgedStruct
}
func bridgeFromObjCDerived(_ s: BridgedClassSub) -> BridgedStruct {
return s // expected-error{{'BridgedClassSub' is not implicitly convertible to 'BridgedStruct'; did you mean to use 'as' to explicitly convert?}}
return s as BridgedStruct
}
// Array -> NSArray
func arrayToNSArray() {
var nsa: NSArray
nsa = [AnyObject]() // expected-error {{cannot assign value of type '[AnyObject]' to type 'NSArray'}}
nsa = [BridgedClass]() // expected-error {{cannot assign value of type '[BridgedClass]' to type 'NSArray'}}
nsa = [OtherClass]() // expected-error {{cannot assign value of type '[OtherClass]' to type 'NSArray'}}
nsa = [BridgedStruct]() // expected-error {{cannot assign value of type '[BridgedStruct]' to type 'NSArray'}}
nsa = [NotBridgedStruct]() // expected-error{{cannot assign value of type '[NotBridgedStruct]' to type 'NSArray'}}
nsa = [AnyObject]() as NSArray
nsa = [BridgedClass]() as NSArray
nsa = [OtherClass]() as NSArray
nsa = [BridgedStruct]() as NSArray
nsa = [NotBridgedStruct]() as NSArray
_ = nsa
}
// NSArray -> Array
func nsArrayToArray(_ nsa: NSArray) {
var arr1: [AnyObject] = nsa // expected-error{{'NSArray' is not implicitly convertible to '[AnyObject]'; did you mean to use 'as' to explicitly convert?}} {{30-30= as [AnyObject]}}
var _: [BridgedClass] = nsa // expected-error{{'NSArray' is not convertible to '[BridgedClass]'}} {{30-30= as! [BridgedClass]}}
var _: [OtherClass] = nsa // expected-error{{'NSArray' is not convertible to '[OtherClass]'}} {{28-28= as! [OtherClass]}}
var _: [BridgedStruct] = nsa // expected-error{{'NSArray' is not convertible to '[BridgedStruct]'}} {{31-31= as! [BridgedStruct]}}
var _: [NotBridgedStruct] = nsa // expected-error{{use 'as!' to force downcast}}
var _: [AnyObject] = nsa as [AnyObject]
var _: [BridgedClass] = nsa as [BridgedClass] // expected-error{{'NSArray' is not convertible to '[BridgedClass]'; did you mean to use 'as!' to force downcast?}} {{31-33=as!}}
var _: [OtherClass] = nsa as [OtherClass] // expected-error{{'NSArray' is not convertible to '[OtherClass]'; did you mean to use 'as!' to force downcast?}} {{29-31=as!}}
var _: [BridgedStruct] = nsa as [BridgedStruct] // expected-error{{'NSArray' is not convertible to '[BridgedStruct]'; did you mean to use 'as!' to force downcast?}} {{32-34=as!}}
var _: [NotBridgedStruct] = nsa as [NotBridgedStruct] // expected-error{{use 'as!' to force downcast}}
var arr6: Array = nsa as Array
arr6 = arr1
arr1 = arr6
}
func dictionaryToNSDictionary() {
// FIXME: These diagnostics are awful.
var nsd: NSDictionary
nsd = [NSObject : AnyObject]() // expected-error {{cannot assign value of type '[NSObject : AnyObject]' to type 'NSDictionary'}}
nsd = [NSObject : AnyObject]() as NSDictionary
nsd = [NSObject : BridgedClass]() // expected-error {{cannot assign value of type '[NSObject : BridgedClass]' to type 'NSDictionary'}}
nsd = [NSObject : BridgedClass]() as NSDictionary
nsd = [NSObject : OtherClass]() // expected-error {{cannot assign value of type '[NSObject : OtherClass]' to type 'NSDictionary'}}
nsd = [NSObject : OtherClass]() as NSDictionary
nsd = [NSObject : BridgedStruct]() // expected-error {{cannot assign value of type '[NSObject : BridgedStruct]' to type 'NSDictionary'}}
nsd = [NSObject : BridgedStruct]() as NSDictionary
nsd = [NSObject : NotBridgedStruct]() // expected-error{{cannot assign value of type '[NSObject : NotBridgedStruct]' to type 'NSDictionary'}}
nsd = [NSObject : NotBridgedStruct]() as NSDictionary
nsd = [NSObject : BridgedClass?]() // expected-error{{cannot assign value of type '[NSObject : BridgedClass?]' to type 'NSDictionary'}}
nsd = [NSObject : BridgedClass?]() as NSDictionary
nsd = [NSObject : BridgedStruct?]() // expected-error{{cannot assign value of type '[NSObject : BridgedStruct?]' to type 'NSDictionary'}}
nsd = [NSObject : BridgedStruct?]() as NSDictionary
nsd = [BridgedClass : AnyObject]() // expected-error {{cannot assign value of type '[BridgedClass : AnyObject]' to type 'NSDictionary'}}
nsd = [BridgedClass : AnyObject]() as NSDictionary
nsd = [OtherClass : AnyObject]() // expected-error {{cannot assign value of type '[OtherClass : AnyObject]' to type 'NSDictionary'}}
nsd = [OtherClass : AnyObject]() as NSDictionary
nsd = [BridgedStruct : AnyObject]() // expected-error {{cannot assign value of type '[BridgedStruct : AnyObject]' to type 'NSDictionary'}}
nsd = [BridgedStruct : AnyObject]() as NSDictionary
nsd = [NotBridgedStruct : AnyObject]() // expected-error{{cannot assign value of type '[NotBridgedStruct : AnyObject]' to type 'NSDictionary'}}
nsd = [NotBridgedStruct : AnyObject]() as NSDictionary
// <rdar://problem/17134986>
var bcOpt: BridgedClass?
nsd = [BridgedStruct() : bcOpt as Any]
bcOpt = nil
_ = nsd
}
// In this case, we should not implicitly convert Dictionary to NSDictionary.
struct NotEquatable {}
func notEquatableError(_ d: Dictionary<Int, NotEquatable>) -> Bool {
return d == d // expected-error{{operator function '==' requires that 'NotEquatable' conform to 'Equatable'}}
}
// NSString -> String
var nss1 = "Some great text" as NSString
var nss2: NSString = ((nss1 as String) + ", Some more text") as NSString
// <rdar://problem/17943223>
var inferDouble = 1.0/10
let d: Double = 3.14159
inferDouble = d
// rdar://problem/17962491
_ = 1 % 3 / 3.0 // expected-error{{'%' is unavailable: For floating point numbers use truncatingRemainder instead}}
var inferDouble2 = 1 / 3 / 3.0
let d2: Double = 3.14159
inferDouble2 = d2
// rdar://problem/18269449
var i1: Int = 1.5 * 3.5 // expected-error {{cannot convert value of type 'Double' to specified type 'Int'}}
// rdar://problem/18330319
func rdar18330319(_ s: String, d: [String : AnyObject]) {
_ = d[s] as! String?
}
// rdar://problem/19551164
func rdar19551164a(_ s: String, _ a: [String]) {}
func rdar19551164b(_ s: NSString, _ a: NSArray) {
rdar19551164a(s, a) // expected-error{{'NSString' is not implicitly convertible to 'String'; did you mean to use 'as' to explicitly convert?}}{{18-18= as String}}
// expected-error@-1{{'NSArray' is not convertible to '[String]'; did you mean to use 'as!' to force downcast?}}{{21-21= as! [String]}}
}
// rdar://problem/19695671
func takesSet<T>(_ p: Set<T>) {} // expected-note {{in call to function 'takesSet'}}
func takesDictionary<K, V>(_ p: Dictionary<K, V>) {} // expected-note {{in call to function 'takesDictionary'}}
func takesArray<T>(_ t: Array<T>) {} // expected-note {{in call to function 'takesArray'}}
func rdar19695671() {
takesSet(NSSet() as! Set) // expected-error{{generic parameter 'T' could not be inferred}}
takesDictionary(NSDictionary() as! Dictionary)
// expected-error@-1 {{generic parameter 'K' could not be inferred}}
// expected-error@-2 {{generic parameter 'V' could not be inferred}}
takesArray(NSArray() as! Array) // expected-error{{generic parameter 'T' could not be inferred}}
}
// This failed at one point while fixing rdar://problem/19600325.
func getArrayOfAnyObject(_: AnyObject) -> [AnyObject] { return [] }
func testCallback(_ f: (AnyObject) -> AnyObject?) {}
testCallback { return getArrayOfAnyObject($0) } // expected-error {{cannot convert value of type '[AnyObject]' to closure result type 'AnyObject?'}}
// <rdar://problem/19724719> Type checker thinks "(optionalNSString ?? nonoptionalNSString) as String" is a forced cast
func rdar19724719(_ f: (String) -> (), s1: NSString?, s2: NSString) {
f((s1 ?? s2) as String)
}
// <rdar://problem/19770981>
func rdar19770981(_ s: String, ns: NSString) {
func f(_ s: String) {}
f(ns) // expected-error{{'NSString' is not implicitly convertible to 'String'; did you mean to use 'as' to explicitly convert?}}{{7-7= as String}}
f(ns as String)
// 'as' has higher precedence than '>' so no parens are necessary with the fixit:
s > ns // expected-error{{'NSString' is not implicitly convertible to 'String'; did you mean to use 'as' to explicitly convert?}}{{9-9= as String}}
_ = s > ns as String
ns > s // expected-error{{'NSString' is not implicitly convertible to 'String'; did you mean to use 'as' to explicitly convert?}}{{5-5= as String}}
_ = ns as String > s
// 'as' has lower precedence than '+' so add parens with the fixit:
s + ns // expected-error{{'NSString' is not implicitly convertible to 'String'; did you mean to use 'as' to explicitly convert?}}{{9-9= as String}}
_ = s + (ns as String)
ns + s // expected-error{{'NSString' is not implicitly convertible to 'String'; did you mean to use 'as' to explicitly convert?}}{{5-5= as String}}
_ = (ns as String) + s
}
// <rdar://problem/19831919> Fixit offers as! conversions that are known to always fail
func rdar19831919() {
var s1 = 1 + "str"; // expected-error{{binary operator '+' cannot be applied to operands of type 'Int' and 'String'}} expected-note{{overloads for '+' exist with these partially matching parameter lists: (Int, Int), (String, String)}}
}
// <rdar://problem/19831698> Incorrect 'as' fixits offered for invalid literal expressions
func rdar19831698() {
var v70 = true + 1 // expected-error@:13 {{cannot convert value of type 'Bool' to expected argument type 'Int'}}
var v71 = true + 1.0 // expected-error{{binary operator '+' cannot be applied to operands of type 'Bool' and 'Double'}}
// expected-note@-1{{overloads for '+'}}
var v72 = true + true // expected-error{{binary operator '+' cannot be applied to two 'Bool' operands}}
// expected-note@-1{{overloads for '+'}}
var v73 = true + [] // expected-error@:13 {{cannot convert value of type 'Bool' to expected argument type 'Array<Bool>'}}
var v75 = true + "str" // expected-error@:13 {{cannot convert value of type 'Bool' to expected argument type 'String'}}
}
// <rdar://problem/19836341> Incorrect fixit for NSString? to String? conversions
func rdar19836341(_ ns: NSString?, vns: NSString?) {
var vns = vns
let _: String? = ns // expected-error{{cannot convert value of type 'NSString?' to specified type 'String?'}}{{22-22= as String?}}
var _: String? = ns // expected-error{{cannot convert value of type 'NSString?' to specified type 'String?'}}{{22-22= as String?}}
// Important part about below diagnostic is that from-type is described as
// 'NSString?' and not '@lvalue NSString?':
let _: String? = vns // expected-error{{cannot convert value of type 'NSString?' to specified type 'String?'}}{{23-23= as String?}}
var _: String? = vns // expected-error{{cannot convert value of type 'NSString?' to specified type 'String?'}}{{23-23= as String?}}
vns = ns
}
// <rdar://problem/20029786> Swift compiler sometimes suggests changing "as!" to "as?!"
func rdar20029786(_ ns: NSString?) {
var s: String = ns ?? "str" as String as String // expected-error{{'NSString' is not implicitly convertible to 'String'; did you mean to use 'as' to explicitly convert?}} {{19-19=(}} {{50-50=) as String}}
// expected-error@-1 {{cannot convert value of type 'String' to expected argument type 'NSString'}} {{50-50= as NSString}}
var s2 = ns ?? "str" as String as String // expected-error {{cannot convert value of type 'String' to expected argument type 'NSString'}}{{43-43= as NSString}}
let s3: NSString? = "str" as String? // expected-error {{cannot convert value of type 'String?' to specified type 'NSString?'}}{{39-39= as NSString?}}
var s4: String = ns ?? "str" // expected-error{{'NSString' is not implicitly convertible to 'String'; did you mean to use 'as' to explicitly convert?}} {{20-20=(}} {{31-31=) as String}}
var s5: String = (ns ?? "str") as String // fixed version
}
// Make sure more complicated cast has correct parenthesization
func castMoreComplicated(anInt: Int?) {
let _: (NSObject & NSCopying)? = anInt // expected-error{{cannot convert value of type 'Int?' to specified type '(NSObject & NSCopying)?'}}{{41-41= as (NSObject & NSCopying)?}}
}
// <rdar://problem/19813772> QoI: Using as! instead of as in this case produces really bad diagnostic
func rdar19813772(_ nsma: NSMutableArray) {
var a1 = nsma as! Array // expected-error{{generic parameter 'Element' could not be inferred in cast to 'Array'}} expected-note {{explicitly specify the generic arguments to fix this issue}} {{26-26=<Any>}}
var a2 = nsma as! Array<AnyObject> // expected-warning{{forced cast from 'NSMutableArray' to 'Array<AnyObject>' always succeeds; did you mean to use 'as'?}} {{17-20=as}}
var a3 = nsma as Array<AnyObject>
}
func rdar28856049(_ nsma: NSMutableArray) {
_ = nsma as? [BridgedClass]
_ = nsma as? [BridgedStruct]
_ = nsma as? [BridgedClassSub]
}
// <rdar://problem/20336036> QoI: Add cast-removing fixit for "Forced cast from 'T' to 'T' always succeeds"
func force_cast_fixit(_ a : [NSString]) -> [NSString] {
return a as! [NSString] // expected-warning {{forced cast of '[NSString]' to same type has no effect}} {{12-27=}}
}
// <rdar://problem/21244068> QoI: IUO prevents specific diagnostic + fixit about non-implicitly converted bridge types
func rdar21244068(_ n: NSString!) -> String {
return n // expected-error {{'NSString' is not implicitly convertible to 'String'; did you mean to use 'as' to explicitly convert?}}
}
func forceBridgeDiag(_ obj: BridgedClass!) -> BridgedStruct {
return obj // expected-error{{'BridgedClass' is not implicitly convertible to 'BridgedStruct'; did you mean to use 'as' to explicitly convert?}}
}
struct KnownUnbridged {}
class KnownClass {}
protocol KnownClassProtocol: class {}
func forceUniversalBridgeToAnyObject<T, U: KnownClassProtocol>(a: T, b: U, c: Any, d: KnownUnbridged, e: KnownClass, f: KnownClassProtocol, g: AnyObject, h: String) {
var z: AnyObject
z = a as AnyObject
z = b as AnyObject
z = c as AnyObject
z = d as AnyObject
z = e as AnyObject
z = f as AnyObject
z = g as AnyObject
z = h as AnyObject
z = a // expected-error{{value of type 'T' expected to be an instance of a class or class-constrained type in assignment}}
z = b
z = c // expected-error{{value of type 'Any' expected to be an instance of a class or class-constrained type in assignment}} expected-note {{cast 'Any' to 'AnyObject'}} {{8-8= as AnyObject}}
z = d // expected-error{{value of type 'KnownUnbridged' expected to be an instance of a class or class-constrained type in assignment}}
z = e
z = f
z = g
z = h // expected-error{{value of type 'String' expected to be an instance of a class or class-constrained type in assignment}}
_ = z
}
func bridgeAnyContainerToAnyObject(x: [Any], y: [NSObject: Any]) {
var z: AnyObject
z = x as AnyObject
z = y as AnyObject
_ = z
}
func bridgeTupleToAnyObject() {
let x = (1, "two")
let y = x as AnyObject
_ = y
}
// Array defaulting and bridging type checking error per rdar://problem/54274245
func rdar54274245(_ arr: [Any]?) {
_ = (arr ?? []) as [NSObject] // expected-warning {{coercion from '[Any]' to '[NSObject]' may fail; use 'as?' or 'as!' instead}}
}
// rdar://problem/60501780 - failed to infer NSString as a value type of a dictionary
func rdar60501780() {
func foo(_: [String: NSObject]) {}
func bar(_ v: String) {
foo(["": "", "": v as NSString])
}
}
| 46.793282 | 236 | 0.697885 |
1e517899b2c28efcec7744fa298a81dbe518e7d7 | 810 | import ARHeadsetKit
extension CubeRenderer {
func updateResources() {
for i in 0..<cubes.count {
cubes[i].isHighlighted = false
}
if let ray = renderer.interactionRay,
let progress = cube.trace(ray: ray) {
cube.isHighlighted = true
if renderer.shortTappingScreen {
let impactLocation = ray.project(progress: progress)
// Speed is in meters per second
cube.collide(location: impactLocation,
direction: ray.direction, speed: 7)
}
} else {
cube.isHighlighted = false
}
cube.update()
cube.render(centralRenderer: centralRenderer)
}
}
| 26.129032 | 68 | 0.502469 |
725db13db244c6c0f490b59892c330b70162742b | 1,091 | //: [Previous](@previous)
//:## Animações Simples
/*:
Vamos fazer de novo nosso BG com o quadradinho azul dentro dele
(dessa vez eu aumentei um pouco o tamanho das coisas, ok?)*/
import UIKit
import PlaygroundSupport
var background = UIView(frame: CGRect(x: 0,y: 0,width: 400,height: 400))
PlaygroundPage.current.liveView = background
background.backgroundColor = UIColor.white
let square = UIView(frame: CGRect(x: 50,y: 50,width: 100,height: 100))
square.backgroundColor = UIColor.blue
background.addSubview(square)
/*:
Pra animar as coisas, a gente usa a UIView.animate, que é um método muito louco, que pra quem usa Flash vai amar
Da mesma forma que o flash, você seta as posições, ou estados finais dos seus objetos da View, e ele vai fazer uma transição contínua até que isso aconteça
*/
UIView.animate(withDuration: 5.0, animations: {
square.backgroundColor = UIColor.blue
square.center = CGPoint(x: 200, y: 200)
})
/*:
Nesse caso, eu só movimentei o meu quadrado da posicao (50, 50) - que é onde ele foi instanciado, para a posição (5, 10)*/
//: [Next](@next)
| 34.09375 | 156 | 0.732356 |
de66e801a801c7fbc5c62c4c5aa6c610aad53a64 | 1,734 | //
// RxSchedulers.swift
// iOS_Bootstrap
//
// Created by Ahmad Mahmoud on 12/21/18.
//
import RxSwift
public struct RxSchedulers {
public static let main = MainScheduler.instance
public static let backgroundConcurrentScheduler = ConcurrentDispatchQueueScheduler(qos: .background)
public let workerScheduler = ConcurrentDispatchQueueScheduler(qos: .default)
public static var imageLoading: SerialDispatchQueueScheduler {
return SerialDispatchQueueScheduler(internalSerialQueueName: "imageLoadingScheduler")
}
public static var backgroundSerialScheduler: SerialDispatchQueueScheduler {
return SerialDispatchQueueScheduler(qos: .background)
}
// static let IO_THREAD = OperationQueueScheduler(operationQueue: )
// static let CurrentThreadScheduler = Schde
// static let ConcurrentMainScheduler = ConcurrentMainScheduler.
// static let CurrentThreadScheduler = CurrentThreadScheduler.instance
//
// static let serialUtility = SerialDispatchQueueScheduler(qos: .utility)
// static let concurrentUtility = ConcurrentDispatchQueueScheduler.init(qos: .utility)
//
// static let serialUser = SerialDispatchQueueScheduler(qos: .userInitiated)
// static let concurrentUser = ConcurrentDispatchQueueScheduler(qos: .userInitiated)
//
// static let serialInteractive = SerialDispatchQueueScheduler(qos: .userInteractive)
// static let concurrentInteractive = ConcurrentDispatchQueueScheduler(qos: .userInteractive)
public static func getCustomSerialBackgroundScheduler(name: String) -> SerialDispatchQueueScheduler {
return SerialDispatchQueueScheduler(internalSerialQueueName: name)
}
}
| 42.292683 | 105 | 0.757209 |
1a95a939af7453370eadc2aa2f3ac9f3ee133ad5 | 13,363 | import CallbackURLKit
import FirebaseMessaging
import Foundation
import PromiseKit
import Shared
import UserNotifications
import XCGLogger
class NotificationManager: NSObject {
func setupNotifications() {
UNUserNotificationCenter.current().delegate = self
}
func resetPushID() -> Promise<String> {
firstly {
Promise<Void> { seal in
Messaging.messaging().deleteToken(completion: seal.resolve)
}
}.then {
Promise<String> { seal in
Messaging.messaging().token(completion: seal.resolve)
}
}
}
func setupFirebase() {
Current.Log.verbose("Calling UIApplication.shared.registerForRemoteNotifications()")
UIApplication.shared.registerForRemoteNotifications()
Messaging.messaging().delegate = self
Messaging.messaging().isAutoInitEnabled = Current.settingsStore.privacy.messaging
}
func didFailToRegisterForRemoteNotifications(error: Error) {
Current.Log.error("failed to register for remote notifications: \(error)")
}
func didRegisterForRemoteNotifications(deviceToken: Data) {
let apnsToken = deviceToken.map { String(format: "%02.2hhx", $0) }.joined()
Current.Log.verbose("Successfully registered for push notifications! APNS token: \(apnsToken)")
Current.crashReporter.setUserProperty(value: apnsToken, name: "APNS Token")
var tokenType: MessagingAPNSTokenType = .prod
if Current.appConfiguration == .Debug {
tokenType = .sandbox
}
Messaging.messaging().setAPNSToken(deviceToken, type: tokenType)
}
func didReceiveRemoteNotification(
userInfo: [AnyHashable: Any],
fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void
) {
Current.Log.verbose("Received remote notification in completion handler!")
Messaging.messaging().appDidReceiveMessage(userInfo)
if let userInfoDict = userInfo as? [String: Any],
let hadict = userInfoDict["homeassistant"] as? [String: Any], let command = hadict["command"] as? String {
switch command {
case "request_location_update":
guard Current.settingsStore.locationSources.pushNotifications else {
Current.Log.info("ignoring request, location source of notifications is disabled")
completionHandler(.noData)
return
}
Current.Log.verbose("Received remote request to provide a location update")
Current.backgroundTask(withName: "push-location-request") { remaining in
Current.api.then(on: nil) { api in
api.GetAndSendLocation(trigger: .PushNotification, maximumBackgroundTime: remaining)
}
}.done { success in
Current.Log.verbose("Did successfully send location when requested via APNS? \(success)")
completionHandler(.newData)
}.catch { error in
Current.Log.error("Error when attempting to submit location update: \(error)")
completionHandler(.failed)
}
case "clear_badge":
Current.Log.verbose("Setting badge to 0 as requested")
UIApplication.shared.applicationIconBadgeNumber = 0
completionHandler(.newData)
case "clear_notification":
Current.Log.verbose("clearing notification for \(userInfo)")
let keys = ["tag", "collapseId"].compactMap { hadict[$0] as? String }
if !keys.isEmpty {
UNUserNotificationCenter.current().removeDeliveredNotifications(withIdentifiers: keys)
}
completionHandler(.newData)
default:
Current.Log.warning("Received unknown command via APNS! \(userInfo)")
completionHandler(.noData)
}
} else {
completionHandler(.failed)
}
}
fileprivate func handleShortcutNotification(
_ shortcutName: String,
_ shortcutDict: [String: String]
) {
var inputParams: CallbackURLKit.Parameters = shortcutDict
inputParams["name"] = shortcutName
Current.Log.verbose("Sending params in shortcut \(inputParams)")
let eventName: String = "ios.shortcut_run"
let deviceDict: [String: String] = [
"sourceDevicePermanentID": Constants.PermanentID, "sourceDeviceName": UIDevice.current.name,
"sourceDeviceID": Current.settingsStore.deviceID,
]
var eventData: [String: Any] = ["name": shortcutName, "input": shortcutDict, "device": deviceDict]
var successHandler: CallbackURLKit.SuccessCallback?
if shortcutDict["ignore_result"] == nil {
successHandler = { params in
Current.Log.verbose("Received params from shortcut run \(String(describing: params))")
eventData["status"] = "success"
eventData["result"] = params?["result"]
Current.Log.verbose("Success, sending data \(eventData)")
Current.api.then(on: nil) { api in
api.CreateEvent(eventType: eventName, eventData: eventData)
}.catch { error -> Void in
Current.Log.error("Received error from createEvent during shortcut run \(error)")
}
}
}
let failureHandler: CallbackURLKit.FailureCallback = { error in
eventData["status"] = "failure"
eventData["error"] = error.XCUErrorParameters
Current.api.then(on: nil) { api in
api.CreateEvent(eventType: eventName, eventData: eventData)
}.catch { error -> Void in
Current.Log.error("Received error from createEvent during shortcut run \(error)")
}
}
let cancelHandler: CallbackURLKit.CancelCallback = {
eventData["status"] = "cancelled"
Current.api.then(on: nil) { api in
api.CreateEvent(eventType: eventName, eventData: eventData)
}.catch { error -> Void in
Current.Log.error("Received error from createEvent during shortcut run \(error)")
}
}
do {
try Manager.shared.perform(
action: "run-shortcut",
urlScheme: "shortcuts",
parameters: inputParams,
onSuccess: successHandler,
onFailure: failureHandler,
onCancel: cancelHandler
)
} catch let error as NSError {
Current.Log.error("Running shortcut failed \(error)")
eventData["status"] = "error"
eventData["error"] = error.localizedDescription
Current.api.then(on: nil) { api in
api.CreateEvent(eventType: eventName, eventData: eventData)
}.catch { error -> Void in
Current.Log.error("Received error from CallbackURLKit perform \(error)")
}
}
}
}
extension NotificationManager: UNUserNotificationCenterDelegate {
private func urlString(from response: UNNotificationResponse) -> String? {
let content = response.notification.request.content
let urlValue = ["url", "uri", "clickAction"].compactMap { content.userInfo[$0] }.first
if let action = content.userInfoActionConfigs.first(
where: { $0.identifier.lowercased() == response.actionIdentifier.lowercased() }
), let url = action.url {
// we only allow the action-specific one to override global if it's set
return url
} else if let openURLRaw = urlValue as? String {
// global url [string], always do it if we aren't picking a specific action
return openURLRaw
} else if let openURLDictionary = urlValue as? [String: String] {
// old-style, per-action url -- for before we could define actions in the notification dynamically
return openURLDictionary.compactMap { key, value -> String? in
if response.actionIdentifier == UNNotificationDefaultActionIdentifier,
key.lowercased() == NotificationCategory.FallbackActionIdentifier {
return value
} else if key.lowercased() == response.actionIdentifier.lowercased() {
return value
} else {
return nil
}
}.first
} else {
return nil
}
}
public func userNotificationCenter(
_ center: UNUserNotificationCenter,
didReceive response: UNNotificationResponse,
withCompletionHandler completionHandler: @escaping () -> Void
) {
Messaging.messaging().appDidReceiveMessage(response.notification.request.content.userInfo)
guard response.actionIdentifier != UNNotificationDismissActionIdentifier else {
Current.Log.info("ignoring dismiss action for notification")
completionHandler()
return
}
let userInfo = response.notification.request.content.userInfo
Current.Log.verbose("User info in incoming notification \(userInfo) with response \(response)")
if let shortcutDict = userInfo["shortcut"] as? [String: String],
let shortcutName = shortcutDict["name"] {
handleShortcutNotification(shortcutName, shortcutDict)
}
if let url = urlString(from: response) {
Current.Log.info("launching URL \(url)")
Current.sceneManager.webViewWindowControllerPromise.done {
$0.open(from: .notification, urlString: url)
}
}
if let info = HomeAssistantAPI.PushActionInfo(response: response) {
Current.backgroundTask(withName: "handle-push-action") { _ in
Current.api.then(on: nil) { api in
api.handlePushAction(for: info)
}
}.ensure {
completionHandler()
}.catch { err -> Void in
Current.Log.error("Error when handling push action: \(err)")
}
} else {
completionHandler()
}
}
public func userNotificationCenter(
_ center: UNUserNotificationCenter,
willPresent notification: UNNotification,
withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void
) {
Messaging.messaging().appDidReceiveMessage(notification.request.content.userInfo)
if notification.request.content.userInfo[XCGLogger.notifyUserInfoKey] != nil,
UIApplication.shared.applicationState != .background {
completionHandler([])
return
}
var methods: UNNotificationPresentationOptions = [.alert, .badge, .sound]
if let presentationOptions = notification.request.content.userInfo["presentation_options"] as? [String] {
methods = []
if presentationOptions.contains("sound") || notification.request.content.sound != nil {
methods.insert(.sound)
}
if presentationOptions.contains("badge") {
methods.insert(.badge)
}
if presentationOptions.contains("alert") {
methods.insert(.alert)
}
}
return completionHandler(methods)
}
public func userNotificationCenter(
_ center: UNUserNotificationCenter,
openSettingsFor notification: UNNotification?
) {
let view = NotificationSettingsViewController()
view.doneButton = true
Current.sceneManager.webViewWindowControllerPromise.done {
var rootViewController = $0.window.rootViewController
if let navigationController = rootViewController as? UINavigationController {
rootViewController = navigationController.viewControllers.first
}
rootViewController?.dismiss(animated: false, completion: {
let navController = UINavigationController(rootViewController: view)
rootViewController?.present(navController, animated: true, completion: nil)
})
}
}
}
extension NotificationManager: MessagingDelegate {
func messaging(_ messaging: Messaging, didReceiveRegistrationToken fcmToken: String?) {
let loggableCurrent = Current.settingsStore.pushID ?? "(null)"
let loggableNew = fcmToken ?? "(null)"
Current.Log.info("Firebase registration token refreshed, new token: \(loggableNew)")
if loggableCurrent != loggableNew {
Current.Log.warning("FCM token has changed from \(loggableCurrent) to \(loggableNew)")
}
Current.crashReporter.setUserProperty(value: fcmToken, name: "FCM Token")
Current.settingsStore.pushID = fcmToken
Current.backgroundTask(withName: "notificationManager-didReceiveRegistrationToken") { _ in
Current.api.then(on: nil) { api in
api.UpdateRegistration()
}
}.cauterize()
}
}
| 40.990798 | 117 | 0.612512 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.