repo_name
stringlengths
6
91
path
stringlengths
6
999
copies
stringclasses
283 values
size
stringlengths
1
7
content
stringlengths
3
1.05M
license
stringclasses
15 values
jam891/ReactKitCatalog
ReactKitCatalog-iOS/Samples/IncrementalSearchViewController.swift
1
3112
// // IncrementalSearchViewController.swift // ReactKitCatalog // // Created by Yasuhiro Inami on 2015/06/01. // Copyright (c) 2015年 Yasuhiro Inami. All rights reserved. // import UIKit import ReactKit import Alamofire import SwiftyJSON private func _searchUrl(query: String) -> String { let escapedQuery = query.stringByAddingPercentEncodingWithAllowedCharacters(.URLHostAllowedCharacterSet()) ?? "" return "https://api.bing.com/osjson.aspx?query=\(escapedQuery)" } private let _reuseIdentifier = "reuseIdentifier" class IncrementalSearchViewController: UITableViewController, UISearchBarDelegate { var searchController: UISearchController? var searchResultStream: Stream<JSON>? var searchResult: [String]? dynamic var searchText: String = "" override func viewDidLoad() { super.viewDidLoad() let searchController = UISearchController(searchResultsController: nil) searchController.dimsBackgroundDuringPresentation = false searchController.searchBar.delegate = self self.tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: _reuseIdentifier) self.tableView.tableHeaderView = searchController.searchBar // http://useyourloaf.com/blog/2015/04/26/search-bar-not-showing-without-a-scope-bar.html searchController.searchBar.sizeToFit() self.searchController = searchController self.searchResultStream = KVO.stream(self, "searchText") // |> peek(print) |> debounce(0.15) |> map { ($0 as? String) ?? "" } // map to Equatable String for `distinctUntilChanged()` |> distinctUntilChanged |> map { query -> Stream<JSON> in let request = Alamofire.request(.GET, URLString: _searchUrl(query), parameters: nil, encoding: .URL) return Stream<JSON>.fromTask(_requestTask(request)) } |> switchLatestInner // REACT self.searchResultStream! ~> print // REACT self.searchResultStream! ~> { [weak self] json in self?.searchResult = json[1].arrayValue.map { $0.stringValue } self?.tableView.reloadData() } } // MARK: - UISearchBarDelegate func searchBar(searchBar: UISearchBar, textDidChange searchText: String) { self.searchText = searchText } // MARK: - UITableViewDataSource override func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return self.searchResult?.count ?? 0 } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier(_reuseIdentifier, forIndexPath: indexPath) cell.textLabel?.text = self.searchResult?[indexPath.row] return cell } }
mit
apple/swift-package-manager
Fixtures/CFamilyTargets/ModuleMapGenerationCases/Package.swift
2
803
// swift-tools-version:4.2 import PackageDescription let package = Package( name: "ModuleMapGenerationCases", targets: [ .target( name: "Baz", dependencies: ["FlatInclude", "NonModuleDirectoryInclude", "UmbrellaHeader", "UmbrellaDirectoryInclude", "UmbrellaHeaderFlat"]), .target( name: "FlatInclude", dependencies: []), .target( name: "NoIncludeDir", dependencies: []), .target( name: "NonModuleDirectoryInclude", dependencies: []), .target( name: "UmbrellaDirectoryInclude", dependencies: []), .target( name: "UmbrellaHeader", dependencies: []), .target( name: "UmbrellaHeaderFlat", dependencies: []), ] )
apache-2.0
blockchain/My-Wallet-V3-iOS
Modules/Platform/Sources/PlatformKit/Services/KYC/Client/KYCTier.swift
1
1527
// Copyright © Blockchain Luxembourg S.A. All rights reserved. import Localization extension KYC.Tier { public var headline: String? { switch self { case .tier2: return LocalizationConstants.KYC.freeCrypto case .tier0, .tier1: return nil } } public var tierDescription: String { switch self { case .tier0: return "Tier Zero Verification" case .tier1: return LocalizationConstants.KYC.tierOneVerification case .tier2: return LocalizationConstants.KYC.tierTwoVerification } } public var requirementsDescription: String { switch self { case .tier1: return LocalizationConstants.KYC.tierOneRequirements case .tier2: return LocalizationConstants.KYC.tierTwoRequirements case .tier0: return "" } } public var limitTimeframe: String { switch self { case .tier0: return "locked" case .tier1: return LocalizationConstants.KYC.annualSwapLimit case .tier2: return LocalizationConstants.KYC.dailySwapLimit } } public var duration: String { switch self { case .tier0: return "0 minutes" case .tier1: return LocalizationConstants.KYC.takesThreeMinutes case .tier2: return LocalizationConstants.KYC.takesTenMinutes } } }
lgpl-3.0
blue42u/swift-t
stc/tests/736-priority-2.swift
4
131
main { foreach i in [1:100] { @prio=i trace_comp(i); } } () trace_comp (int x) { wait (x) { trace(x); } }
apache-2.0
googlecodelabs/admob-native-advanced-feed
ios/final/NativeAdvancedTableViewExample/MenuItem.swift
1
1543
// // Copyright (C) 2017 Google, 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. // import UIKit class MenuItem { var name: String var description: String var price: String var category: String var photo: UIImage init(name: String, description: String, price: String, category: String, photo: UIImage) { // Initialize stored properties. self.name = name self.description = description self.price = price self.category = category self.photo = photo } convenience init?(dictionary: [String: Any]) { guard let name = dictionary["name"] as? String, let description = dictionary["description"] as? String, let price = dictionary["price"] as? String, let category = dictionary["category"] as? String, let photoFileName = dictionary["photo"] as? String, let photo = UIImage(named: photoFileName) else { return nil; } self.init(name: name, description: description, price: price, category: category, photo: photo) } }
apache-2.0
mvandervelden/iOSSystemIntegrationsDemo
SearchDemoTests/SearchDemoTests.swift
2
474
import XCTest @testable import SearchDemo class SearchDemoTests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. } 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() { } }
mit
rizumita/ResourceInstantiatable
ResourceInstantiatable/NibInstantiator.swift
1
676
// // NibInstantiator.swift // ResourceInstantiatable // // Created by 和泉田 領一 on 2015/09/28. // Copyright © 2015年 CAPH. All rights reserved. // import Foundation public struct NibInstantiator<T: UIView>: ResourceInstantiatable { public typealias InstanceType = T let name: String let bundle: NSBundle public func instantiate() throws -> InstanceType { let nib = UINib(nibName: name, bundle: bundle) return nib.instantiateWithOwner(nil, options: nil).first as! InstanceType } init(name: String, bundle: NSBundle = NSBundle.mainBundle()) { self.name = name self.bundle = bundle } }
mit
AlexHmelevski/AHContainerViewController
AHContainerViewController/Classes/DimmingViewModel.swift
1
1784
// // DimmingViewModel.swift // AHContainerViewController // // Created by Alex Hmelevski on 2017-07-12. // import Foundation public enum DimmingViewType { case defaultView case defaultBlur(UIBlurEffect.Style) case noDimming } public struct DimmingViewModel { let view: UIView let animation: (CGFloat) -> (() -> Void) } protocol DimmingViewFactory { func view(for type: DimmingViewType) -> DimmingViewModel? } public class ALModalPresentationControllerDimmingViewFactory: DimmingViewFactory { func view(for type: DimmingViewType) -> DimmingViewModel? { switch type { case let .defaultBlur(style): return defaultBlur(with: style) case .defaultView: return defaultDimming default: return nil } } private var defaultDimming: DimmingViewModel { let dimmingView = UIView() dimmingView.backgroundColor = UIColor(white: 0, alpha: 0.7) dimmingView.alpha = 0 let animationBlock: (CGFloat) -> ( () -> Void ) = { (alpha) in return { dimmingView.alpha = alpha } } return DimmingViewModel(view: dimmingView, animation: animationBlock) } private func defaultBlur(with style: UIBlurEffect.Style) -> DimmingViewModel { let view = UIVisualEffectView() view.effect = nil let animationBlock: (CGFloat) -> (() -> Void) = { (alpha) in return { view.effect = alpha <= 0 ? nil : UIBlurEffect(style: style) } } return DimmingViewModel(view: view, animation: animationBlock) } private var defaultPropertyAnimator: UIViewPropertyAnimator { let animator = UIViewPropertyAnimator() return animator } }
mit
hamilyjing/JJSwiftStudy
Playground/AnyClass.playground/Contents.swift
1
1023
//: Playground - noun: a place where people can play import UIKit // AnyClass: 类类型,可以动态创建类对象和调用类方法 class A { class func method() { print("Hello") } } let typeA: A.Type = A.self // 在 Swift 中,.self 可以用在类型后面取得类型本身,也可以用在某个实例后面取得这个实例本身。 print(typeA) // A typeA.method() // 或者 let anyClass: AnyClass = A.self (anyClass as! A.Type).method() class MusicViewController: UIViewController { } class AlbumViewController: UIViewController { } let usingVCTypes: [AnyClass] = [MusicViewController.self, AlbumViewController.self] func setupViewControllers(_ vcTypes: [AnyClass]) { for vcType in vcTypes { if vcType is UIViewController.Type { let vc = (vcType as! UIViewController.Type).init() // 通过这种方式初始化对象的时候,必须有required 修饰的初始化方法才行 print(vc) } } } setupViewControllers(usingVCTypes)
mit
SpiciedCrab/MGRxKitchen
MGRxKitchen/Classes/RxMogoForNetworkingProcessing/RxMogo+PagableSpore.swift
1
6486
// // RxMogo+PagableSpore.swift // Pods // // Created by Harly on 2017/9/16. // // import UIKit import Result import RxSwift import RxCocoa import MGBricks import HandyJSON public protocol PageBase: NeedHandleRequestError, HaveRequestRx { // MARK: - Inputs /// 全部刷新,上拉或者刚进来什么的 var firstPage: PublishSubject<Void> { get set } /// 下一页能量 var nextPage: PublishSubject<Void> { get set } /// 最后一页超级能量 var finalPageReached: PublishSubject<Void> { get set } func basePagedRequest<Element>(request : @escaping (MGPage) -> Observable<Result<([Element], MGPage), MGAPIError>>)-> Observable<[Element]> } extension PageBase { public func basePagedRequest<Element>(request : @escaping (MGPage) -> Observable<Result<([Element], MGPage), MGAPIError>>)-> Observable<[Element]> { return base(request: request) } func base<Element>(request : @escaping (MGPage) -> Observable<Result<([Element], MGPage), MGAPIError>>)-> Observable<[Element]> { let loadNextPageTrigger: (Driver<MGPageRepositoryState<Element>>) -> Driver<()> = { state in return self.nextPage.asDriver(onErrorJustReturn: ()).withLatestFrom(state).do(onNext: { state in if let page = state.pageInfo , page.currentPage >= page.totalPage { self.finalPageReached.onNext(()) } }).flatMap({ state -> Driver<()> in !state.shouldLoadNextPage ? Driver.just(()) : Driver.empty() }) } let performSearch: ((MGPage) -> Observable<PageResponse<Element>>) = {[weak self] page -> Observable<Result<([Element], MGPage), MGAPIError>> in guard let strongSelf = self else { return Observable.empty() } return strongSelf.trackRequest(signal: request(page)) } let repo = pagableRepository(allRefresher: firstPage.asDriver(onErrorJustReturn: ()), loadNextPageTrigger: loadNextPageTrigger, performSearch: performSearch) {[weak self] (error) in guard let strongSelf = self else { return } strongSelf.errorProvider .onNext(RxMGError(identifier: "pageError", apiError: error)) } return repo.asObservable() .do(onNext: { element in print(element) }) .map { $0.repositories } .map { $0.value } } } /// 分页实现 public protocol PagableRequest: PageBase { // MARK: - Outputs /// 获取page /// /// - Parameter request: pureRequest之类的 /// - Returns: Observable T func pagedRequest<Element>(request : @escaping (MGPage) -> Observable<Result<([Element], MGPage), MGAPIError>>)-> Observable<[Element]> } // MARK: - Page public extension PagableRequest { public func pagedRequest<Element>(request : @escaping (MGPage) -> Observable<Result<([Element], MGPage), MGAPIError>>)-> Observable<[Element]> { return basePagedRequest(request: request) } } /// Page Extension public protocol PageableJSONRequest: PageBase { associatedtype PageJSONType /// 整个请求对象类型 var jsonOutputer: PublishSubject<PageJSONType> { get set } } extension PageableJSONRequest { /// page请求究极体 /// /// - Parameters: /// - request: 你的request /// - resolver: resolver,告诉我你的list是哪个 /// - Returns: 原来的Observer public func pagedRequest<Element>( request : @escaping (MGPage) -> Observable<Result<([String : Any], MGPage), MGAPIError>>, resolver : @escaping (PageJSONType) -> [Element]) -> Observable<[Element]> where PageJSONType : HandyJSON { func pageInfo(page: MGPage) -> Observable<Result<([Element], MGPage), MGAPIError>> { let pageRequest = request(page).map({[weak self] result -> Result<([Element], MGPage), MGAPIError> in guard let strongSelf = self else { return Result(error: MGAPIError("000", message: "")) } switch result { case .success(let obj) : let pageObj = PageJSONType.deserialize(from: obj.0 as NSDictionary) ?? PageJSONType() let pageArray = resolver(pageObj) strongSelf.jsonOutputer.onNext(pageObj) return Result(value: (pageArray, obj.1)) case .failure : return Result(error: result.error ?? MGAPIError("000", message: "不明错误出现咯")) } }) return pageRequest } return basePagedRequest(request: { page -> Observable<Result<([Element], MGPage), MGAPIError>> in return pageInfo(page: page) }) } } /// Page Extension public protocol PageExtensible: class { var pageOutputer: PublishSubject<MGPage> { get set } } extension PageBase where Self : PageExtensible { public func basePagedRequest<Element>(request : @escaping (MGPage) -> Observable<Result<([Element], MGPage), MGAPIError>>)-> Observable<[Element]> { func pageInfo(page: MGPage) -> Observable<Result<([Element], MGPage), MGAPIError>> { let pageRequest = request(page).map({[weak self] result -> Result<([Element], MGPage), MGAPIError> in guard let strongSelf = self else { return Result(error: MGAPIError("000", message: "")) } switch result { case .success(let obj) : strongSelf.pageOutputer.onNext(obj.1) return Result(value: (obj.0, obj.1)) case .failure : return Result(error: result.error ?? MGAPIError("000", message: "不明错误出现咯")) } }) return pageRequest } return base(request: { page -> Observable<Result<([Element], MGPage), MGAPIError>> in return pageInfo(page: page) }) } }
mit
prolificinteractive/simcoe
SimcoeTests/TrackerTests.swift
1
4672
// // RecorderTests.swift // Simcoe // // Created by Christopher Jones on 2/21/16. // Copyright © 2016 Prolific Interactive. All rights reserved. // import XCTest @testable import Simcoe class TrackerTests: XCTestCase { var simcoe: Simcoe! var outputSource: OutputFake! override func setUp() { outputSource = OutputFake() simcoe = Simcoe(tracker: Tracker(outputSources: [outputSource])) } func test_recording_to_default_providers() { let tracker = PageViewTrackingFake() simcoe.providers = [tracker] let expectation = 1 simcoe.track(pageView: "test", withAdditionalProperties: nil, providers: nil) XCTAssertEqual(expectation, outputSource.printCallCount, "Expected result = \(expectation); got \(outputSource.printCallCount)") } func test_recording_to_input_providers() { let trackerOne = PageViewTrackingFake() simcoe.providers = [trackerOne] let expectation = 3 simcoe.track(pageView: "test", withAdditionalProperties: nil, providers: [trackerOne, PageViewTrackingFake(), PageViewTrackingFake()]) XCTAssertEqual(expectation, outputSource.printCallCount, "Expected result = \(expectation); got \(outputSource.printCallCount)") } func test_that_it_records_events() { let tracker = PageViewTrackingFake() simcoe.providers = [tracker] let expectation = 1 simcoe.track(pageView: "1234") XCTAssertEqual(expectation, outputSource.printCallCount, "Expected result = \(expectation); got \(outputSource.printCallCount)") } func test_that_it_does_not_write_when_option_none() { simcoe.providers = [PageViewTrackingFake(), PageViewTrackingFake(), PageViewTrackingFake()] simcoe.tracker.outputOption = .none let expectation = 0 simcoe.track(pageView: "1234") XCTAssertEqual(expectation, outputSource.printCallCount, "Expected result = \(expectation); got \(outputSource.printCallCount)") } func test_that_it_writes_to_output_once_when_option_simple() { simcoe.providers = [PageViewTrackingFake(), PageViewTrackingFake(), PageViewTrackingFake()] simcoe.tracker.outputOption = .simple let expectation = 1 simcoe.track(pageView: "1234") XCTAssertEqual(expectation, outputSource.printCallCount, "Expected result = \(expectation); got \(outputSource.printCallCount)") } func test_that_it_writes_to_output_for_each_provider_when_option_verbose() { simcoe.providers = [PageViewTrackingFake(), PageViewTrackingFake(), PageViewTrackingFake()] simcoe.tracker.outputOption = .verbose let expectation = simcoe.providers.count simcoe.track(pageView: "1234") XCTAssertEqual(expectation, outputSource.printCallCount, "Expected result = \(expectation); got \(outputSource.printCallCount)") } func test_that_it_does_not_log_errors_when_option_suppress() { let pageViewTracker = PageViewTrackingFake() pageViewTracker.shouldFail = true simcoe.providers = [pageViewTracker] simcoe.tracker.errorOption = .suppress let expectation = 0 simcoe.track(pageView: "page view test") XCTAssertEqual(expectation, outputSource.printCallCount, "Expected result = \(expectation); got \(outputSource.printCallCount)") } func test_that_it_logs_errors_when_option_default() { let pageViewTracker = PageViewTrackingFake() pageViewTracker.shouldFail = true simcoe.providers = [pageViewTracker] simcoe.tracker.errorOption = .default let expectation = 1 simcoe.track(pageView: "1234") XCTAssertEqual(expectation, outputSource.printCallCount, "Expected result = \(expectation); got \(outputSource.printCallCount)") } func test_that_it_logs_one_error_per_provider_when_option_default() { let pageViewTrackers = [PageViewTrackingFake(), PageViewTrackingFake(), PageViewTrackingFake()] for tracker in pageViewTrackers { tracker.shouldFail = true } simcoe.providers = pageViewTrackers.map({ $0 as AnalyticsTracking }) // Cast fixes weird array assignment crash simcoe.tracker.errorOption = .default let expectation = pageViewTrackers.count simcoe.track(pageView: "1234") XCTAssertEqual(expectation, outputSource.printCallCount, "Expected result = \(expectation); got \(outputSource.printCallCount)") } }
mit
AliSoftware/SwiftGen
Sources/TestUtils/Fixtures/Generated/Strings/structured-swift5/plurals.swift
2
1884
// swiftlint:disable all // Generated using SwiftGen — https://github.com/SwiftGen/SwiftGen import Foundation // swiftlint:disable superfluous_disable_command file_length implicit_return // MARK: - Strings // swiftlint:disable explicit_type_interface function_parameter_count identifier_name line_length // swiftlint:disable nesting type_body_length type_name vertical_whitespace_opening_braces internal enum L10n { internal enum Apples { /// Plural format key: "%#@apples@" internal static func count(_ p1: Int) -> String { return L10n.tr("Localizable", "apples.count", p1) } } internal enum Competition { internal enum Event { /// Plural format key: "%#@Matches@" internal static func numberOfMatches(_ p1: Int) -> String { return L10n.tr("Localizable", "competition.event.number-of-matches", p1) } } } internal enum Feed { internal enum Subscription { /// Plural format key: "%#@Subscriptions@" internal static func count(_ p1: Int) -> String { return L10n.tr("Localizable", "feed.subscription.count", p1) } } } } // swiftlint:enable explicit_type_interface function_parameter_count identifier_name line_length // swiftlint:enable nesting type_body_length type_name vertical_whitespace_opening_braces // MARK: - Implementation Details extension L10n { private static func tr(_ table: String, _ key: String, _ args: CVarArg...) -> String { let format = BundleToken.bundle.localizedString(forKey: key, value: nil, table: table) return String(format: format, locale: Locale.current, arguments: args) } } // swiftlint:disable convenience_type private final class BundleToken { static let bundle: Bundle = { #if SWIFT_PACKAGE return Bundle.module #else return Bundle(for: BundleToken.self) #endif }() } // swiftlint:enable convenience_type
mit
hackersatcambridge/hac-website
Sources/HaCWebsiteLib/Events/EventServer.swift
1
793
import Foundation public struct EventServer { static func getAllEvents() -> [GeneralEvent] { let newEvents = try? GeneralEvent.makeQuery().all() return newEvents ?? [] } static func getCurrentlyHypedEvents() -> [GeneralEvent] { let currentDate = Date() let newEvents = try? GeneralEvent.makeQuery() .filter("hypeStartDate", .lessThanOrEquals, currentDate) .filter("hypeEndDate", .greaterThanOrEquals, currentDate) .all() return newEvents ?? [] } static func getEvents(from fromDate: Date, to toDate: Date) -> [GeneralEvent] { let newEvents = try? GeneralEvent.makeQuery() .filter("hypeStartDate", .lessThanOrEquals, toDate) .filter("hypeEndDate", .greaterThanOrEquals, fromDate) .all() return newEvents ?? [] } }
mit
coinbase/coinbase-ios-sdk
Source/DataProviders/AccessTokenProvider.swift
1
482
// // AccessTokenProvider.swift // CoinbaseSDK // // Copyright © 2018 Coinbase, Inc. All rights reserved. // import Foundation /// Provides access token. public class AccessTokenProvider { /// Access token. public var accessToken: String? /// Creates a new instance from given parameters. /// /// - Parameter accessToken: Access token. /// public init(accessToken: String? = nil) { self.accessToken = accessToken } }
apache-2.0
ZamzamInc/ZamzamKit
Sources/ZamzamCore/Logging/Services/LogServiceOS.swift
1
1714
// // LogServiceOS.swift // ZamzamCore // // Created by Basem Emara on 2019-11-01. // Copyright © 2019 Zamzam Inc. All rights reserved. // import os /// Sends a message to the logging system, optionally specifying a custom log object, log level, and any message format arguments. public struct LogServiceOS: LogService { public let minLevel: LogAPI.Level private let subsystem: String private let category: String private let log: OSLog private let isDebug: Bool public init(minLevel: LogAPI.Level, subsystem: String, category: String, isDebug: Bool) { self.minLevel = minLevel self.subsystem = subsystem self.category = category self.log = OSLog(subsystem: subsystem, category: category) self.isDebug = isDebug } } public extension LogServiceOS { func write( _ level: LogAPI.Level, with message: String, file: String, function: String, line: Int, error: Error?, context: [String: CustomStringConvertible] ) { let type: OSLogType switch level { case .verbose: type = .debug case .debug: type = .debug case .info: type = .info case .warning: type = .default case .error: type = .error case .none: return } // Expose message in Console app if debug mode if isDebug { os_log("%{public}s", log: log, type: type, format(message, file, function, line, error, context)) return } os_log("%@", log: log, type: type, format(message, file, function, line, error, context)) } }
mit
tomasharkema/HoelangTotTrein.iOS
Pods/Observable-Swift/Observable-Swift/ObservableReference.swift
17
576
// // ObservableReference.swift // Observable-Swift // // Created by Leszek Ślażyński on 21/06/14. // Copyright (c) 2014 Leszek Ślażyński. All rights reserved. // public class ObservableReference<T> : ObservableProxy<T, Observable<T>>, WritableObservable { public typealias ValueType = T internal var storage : Observable<T> public override var value: T { get { return storage.value } set { storage.value = newValue } } public init (_ v : T) { storage = Observable(v) super.init(storage) } }
apache-2.0
coinbase/coinbase-ios-sdk
Source/Network/Models/Response.swift
1
945
// // Response.swift // Coinbase // // Copyright © 2018 Coinbase, Inc. All rights reserved. // import Foundation /// Used to store all data associated with a serialized response. public class Response<Value>: DefaultResponse { /// The result of response serialization. public let result: Result<Value> /// Creates a new instance from given parameters. /// /// - Parameters: /// - request: The URL request sent to the server. /// - response: The server's response to the URL request. /// - data: The data returned by the server. /// - result: The result of response serialization. /// public init(request: URLRequest?, response: HTTPURLResponse?, data: Data?, result: Result<Value>) { self.result = result super.init(request: request, response: response, data: data, error: result.error) } }
apache-2.0
abstractmachine/Automatic.Writer
AutomaticWriter/AutomatParser/HighlightToken.swift
1
1940
// // HighlightToken.swift // AutomaticWriter // // Created by Raphael on 18.02.15. // Copyright (c) 2015 HEAD Geneva. All rights reserved. // import Foundation enum HighlightType { case NONE, TITLE, CSSIMPORT, JSIMPORT, AUTOMATIMPORT, BLOCKTAG, INLINETAG, OPENINGBLOCKTAG, OPENINGINLINETAG, CLOSINGBLOCKTAG, CLOSINGINLINETAG, EVENT, TWINE, JSDECLARATION, JS, COMMENT var description:String { switch self { case NONE: return "NONE" case TITLE: return "TITLE" case CSSIMPORT: return "CSSIMPORT" case JSIMPORT: return "JSIMPORT" case AUTOMATIMPORT: return "AUTOMATIMPORT" case BLOCKTAG: return "BLOCKTAG" case INLINETAG: return "INLINETAG" case OPENINGBLOCKTAG: return "OPENINGBLOCKTAG" case OPENINGINLINETAG: return "OPENINGINLINETAG" case CLOSINGBLOCKTAG: return "CLOSINGBLOCKTAG" case CLOSINGINLINETAG: return "CLOSINGINLINETAG" case EVENT: return "EVENT" case TWINE: return "TWINE" case JSDECLARATION: return "JSDECLARATION" case JS: return "JS" case COMMENT: return "COMMENT" } } } // A HiglightToken is an object made of the result of a search with a Regular Expression // the ranges are the regular expression's capture groups // the type allows the software to apply are different highlighting for each type class HighlightToken : CustomStringConvertible { let ranges:[NSRange] let type:HighlightType init(_ranges:[NSRange], _type:HighlightType) { ranges = _ranges type = _type } var description:String { return "Token type: \"\(type.description)\", with range 0:{loc:\(ranges[0].location), len:\(ranges[0].length)}" } }
mit
alexaubry/BulletinBoard
Sources/Support/Animations/AnimationChain.swift
1
3976
/** * BulletinBoard * Copyright (c) 2017 - present Alexis Aubry. Licensed under the MIT license. */ import Foundation import UIKit // MARK: AnimationChain /** * A sequence of animations where animations are executed the one after the other. * * Animations are represented by `AnimationPhase` objects, that contain the code of the animation, * its duration relative to the chain duration, their curve and their individual completion handlers. */ public class AnimationChain { /// The total duration of the animation chain. public let duration: TimeInterval /// The initial delay before the animation chain starts. public var initialDelay: TimeInterval = 0 /// The code to execute after animation chain is executed. public var completionHandler: () -> Void /// Whether the chain is being run. public private(set) var isRunning: Bool = false // MARK: Initialization private var animations: [AnimationPhase] = [] private var didFinishFirstAnimation: Bool = false /** * Creates an animation chain with the specified duration. */ public init(duration: TimeInterval) { self.duration = duration self.completionHandler = {} } // MARK: - Interacting with the Chain /** * Add an animation at the end of the chain. * * You cannot add animations if the chain is running. * * - parameter animation: The animation phase to add. */ public func add(_ animation: AnimationPhase) { precondition(!isRunning, "Cannot add an animation to the chain because it is already performing.") animations.append(animation) } /** * Starts the animation chain. */ public func start() { precondition(!isRunning, "Animation chain already running.") isRunning = true performNextAnimation() } private func performNextAnimation() { guard animations.count > 0 else { completeGroup() return } let animation = animations.removeFirst() let duration = animation.relativeDuration * self.duration let options = UIView.AnimationOptions(rawValue: UInt(animation.curve.rawValue << 16)) let delay: TimeInterval = didFinishFirstAnimation ? 0 : initialDelay UIView.animate(withDuration: duration, delay: delay, options: options, animations: animation.block) { _ in self.didFinishFirstAnimation = true animation.completionHandler() self.performNextAnimation() } } private func completeGroup() { isRunning = false completionHandler() } } // MARK: - AnimationPhase /** * A member of an `AnimationChain`, representing a single animation. * * Set the `block` property to a block containing the animations. Set the `completionHandler` with * a block to execute at the end of the animation. The default values do nothing. */ public class AnimationPhase { /** * The duration of the animation, relative to the total duration of the chain. * * Must be between 0 and 1. */ public let relativeDuration: TimeInterval /** * The animation curve. */ public let curve: UIView.AnimationCurve /** * The animation code. */ public var block: () -> Void /** * A block to execute at the end of the animation. */ public var completionHandler: () -> Void // MARK: Initialization /** * Creates an animtion phase object. * * - parameter relativeDuration: The duration of the animation, as a fraction of the total chain * duration. Must be between 0 and 1. * - parameter curve: The animation curve */ public init(relativeDuration: TimeInterval, curve: UIView.AnimationCurve) { self.relativeDuration = relativeDuration self.curve = curve self.block = {} self.completionHandler = {} } }
mit
askfromap/PassCodeLock-Swift3
PasscodeLock/PasscodeLock/EnterPasscodeState.swift
1
1881
// // EnterPasscodeState.swift // PasscodeLock // // Created by Yanko Dimitrov on 8/28/15. // Copyright © 2015 Yanko Dimitrov. All rights reserved. // import Foundation public let PasscodeLockIncorrectPasscodeNotification = "passcode.lock.incorrect.passcode.notification" struct EnterPasscodeState: PasscodeLockStateType { let title: String let description: String let isCancellableAction: Bool var isTouchIDAllowed = true fileprivate var inccorectPasscodeAttempts = 0 fileprivate var isNotificationSent = false init(allowCancellation: Bool = true) { isCancellableAction = allowCancellation title = localizedStringFor("PasscodeLockEnterTitle", comment: "Enter passcode title") description = localizedStringFor("PasscodeLockEnterDescription", comment: "Enter passcode description") } mutating func acceptPasscode(_ passcode: String, fromLock lock: PasscodeLockType) { guard let currentPasscode = lock.repository.passcode else { return } if passcode == currentPasscode { lock.delegate?.passcodeLockDidSucceed(lock) } else { inccorectPasscodeAttempts += 1 if inccorectPasscodeAttempts >= lock.configuration.maximumInccorectPasscodeAttempts { postNotification() } lock.delegate?.passcodeLockDidFail(lock) } } fileprivate mutating func postNotification() { guard !isNotificationSent else { return } let center = NotificationCenter.default center.post(name: Notification.Name(rawValue: PasscodeLockIncorrectPasscodeNotification), object: nil) isNotificationSent = true } }
mit
OrangeJam/iSchool
iSchool/AssignmentCell.swift
1
1318
// // AssignmentCell.swift // iSchool // // Created by Kári Helgason on 19/10/14. // Copyright (c) 2014 OrangeJam. All rights reserved. // import Foundation class AssignmentsTableViewCell : UITableViewCell { @IBOutlet weak var nameLabel: UILabel! @IBOutlet weak var courseLabel: UILabel! @IBOutlet weak var dueDateLabel: UILabel! @IBOutlet weak var doneImage: UIImageView! @IBOutlet weak var notDoneImage: UIImageView! func setAssignment(a: Assignment) { let dateFormatter = NSDateFormatter() dateFormatter.dateFormat = "dd.MM" dueDateLabel.text = dateFormatter.stringFromDate(a.dueDate) nameLabel.text = a.name courseLabel.text = a.courseName if dateFormatter.stringFromDate(NSDate()) == "01.04"{ if a.handedIn { doneImage.hidden = true notDoneImage.hidden = false } else { doneImage.hidden = false notDoneImage.hidden = true } } else { if a.handedIn { doneImage.hidden = false notDoneImage.hidden = true } else { doneImage.hidden = true notDoneImage.hidden = false } } } }
bsd-3-clause
kuangniaokuang/Cocktail-Pro
smartmixer/smartmixer/Ingridients/IngredientDetail.swift
1
5973
// // MaterialDetail.swift // smartmixer // // Created by 姚俊光 on 14-8-24. // Copyright (c) 2014年 Smart Group. All rights reserved. // import UIKit import CoreData class IngredientDetail: UIViewController { @IBOutlet var image:UIImageView! @IBOutlet var myscrollView:UIScrollView! @IBOutlet var navtitle:UINavigationItem! @IBOutlet var name:UILabel! @IBOutlet var nameEng:UILabel! @IBOutlet var iHave:UIImageView! @IBOutlet var desc:UITextView! @IBOutlet var alcohol:UILabel! @IBOutlet var showBt:UIButton! //描述的高度 @IBOutlet var hDesc: NSLayoutConstraint! //主框架的高度 @IBOutlet var hMainboard: NSLayoutConstraint! //当前的材料 var ingridient:Ingridient! override func viewDidLoad() { //self super.viewDidLoad() self.navigationController?.navigationBar.tintColor = UIColor.whiteColor() if(ingridient != nil){ navtitle.title = ingridient.name name.text = ingridient.name nameEng.text = ingridient.nameEng if(ingridient.ihave == true){ iHave.image = UIImage(named: "Heartyes.png") }else{ iHave.image = UIImage(named: "Heartno.png") } desc.text = ingridient.desc var size = ingridient.desc.textSizeWithFont(self.desc!.font!, constrainedToSize: CGSize(width:300, height:1000)) if(size.height<100){ showBt.hidden = true } image.image = UIImage(named: ingridient.thumb) } if(deviceDefine==""){//添加向右滑动返回 var slideback = UISwipeGestureRecognizer() slideback.addTarget(self, action: "SwipeToBack:") slideback.direction = UISwipeGestureRecognizerDirection.Right self.view.addGestureRecognizer(slideback) self.view.userInteractionEnabled = true } } override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() if(myscrollView != nil){ myscrollView.contentSize = CGSize(width: 320, height: 900) self.view.layoutIfNeeded() } } class func IngredientDetailInit()->IngredientDetail{ var ingredientDetail = UIStoryboard(name:"Ingredients"+deviceDefine,bundle:nil).instantiateViewControllerWithIdentifier("ingredientDetail") as IngredientDetail return ingredientDetail } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } func SwipeToBack(sender:UISwipeGestureRecognizer){ self.navigationController?.popViewControllerAnimated(true) } @IBAction func back(sender: UIBarButtonItem) { self.navigationController?.popViewControllerAnimated(true) } var webView:WebView! @IBAction func tuBuy(sender: UIButton){ webView=WebView.WebViewInit() webView.WebTitle="商城" self.navigationController?.pushViewController(webView, animated: true) } //我有按钮发生了点击 @IBAction func haveClick(sender:UIButton){ ingridient.ihave = !ingridient.ihave.boolValue if(ingridient.ihave == true){ iHave.image = UIImage(named: "Heartyes.png") UserHome.addHistory(2, id: ingridient.id.integerValue, thumb: ingridient.thumb, name: ingridient.name) }else{ iHave.image = UIImage(named: "Heartno.png") UserHome.removeHistory(2, id: ingridient.id.integerValue) } var error: NSError? = nil if !managedObjectContext.save(&error) { abort() } } //显示所有的文字 @IBAction func showAllText(sender:UIButton){ if(hMainboard.constant == 250){ var str:String = desc.text! var size = str.textSizeWithFont(desc!.font!, constrainedToSize: CGSize(width:300, height:1000)) if(size.height > (hDesc!.constant-20)){ /**/ UIView.animateWithDuration(0.4, animations: { self.hMainboard.constant = 150 + size.height; self.hDesc.constant = size.height + 20; self.view.layoutIfNeeded(); }, completion: { _ in sender.titleLabel!.text = "《收起"; }) /**/ } }else{ /**/ UIView.animateWithDuration(0.4, animations: { self.hMainboard.constant = 250 self.hDesc.constant = 125 self.view.layoutIfNeeded() }, completion: { _ in sender.titleLabel!.text = "全部》" }) /**/ } } func collectionView(collectionView: UICollectionView!, numberOfItemsInSection section: Int) -> Int { //let sectionInfo = self.fetchedResultsController.sections[section] as NSFetchedResultsSectionInfo //return sectionInfo.numberOfObjects return 0 } func collectionView(collectionView: UICollectionView!, cellForItemAtIndexPath indexPath: NSIndexPath!) -> UICollectionViewCell! { var row = indexPath.row var session = indexPath.section var cell = collectionView.dequeueReusableCellWithReuseIdentifier("aboutRecipe", forIndexPath: indexPath) as UICollectionViewCell return cell } func collectionView(collectionView: UICollectionView!, didSelectItemAtIndexPath indexPath: NSIndexPath!) { var cell = collectionView.cellForItemAtIndexPath(indexPath) as IngredientThumb var materials = UIStoryboard(name:"Ingredients",bundle:nil).instantiateViewControllerWithIdentifier("ingredientDetail") as IngredientDetail //self.navigationController.pushViewController(materials, animated: true) } }
apache-2.0
nathawes/swift
test/Reflection/typeref_lowering.swift
20
95674
// REQUIRES: no_asan // XFAIL: OS=windows-msvc // RUN: %empty-directory(%t) // UNSUPPORTED: CPU=arm64e // RUN: %target-build-swift -Xfrontend -disable-availability-checking %S/Inputs/TypeLowering.swift -parse-as-library -emit-module -emit-library -module-name TypeLowering -o %t/%target-library-name(TypesToReflect) // RUN: %target-build-swift -Xfrontend -disable-availability-checking %S/Inputs/TypeLowering.swift %S/Inputs/main.swift -emit-module -emit-executable -module-name TypeLowering -o %t/TypesToReflect // RUN: %target-swift-reflection-dump -binary-filename %t/%target-library-name(TypesToReflect) -binary-filename %platform-module-dir/%target-library-name(swiftCore) -dump-type-lowering < %s | %FileCheck %s --check-prefix=CHECK-%target-ptrsize // RUN: %target-swift-reflection-dump -binary-filename %t/TypesToReflect -binary-filename %platform-module-dir/%target-library-name(swiftCore) -dump-type-lowering < %s | %FileCheck %s --check-prefix=CHECK-%target-ptrsize 12TypeLowering11BasicStructV // CHECK-64: (struct TypeLowering.BasicStruct) // CHECK-64-NEXT: (struct size=16 alignment=4 stride=16 num_extra_inhabitants=0 bitwise_takable=1 // CHECK-64-NEXT: (field name=i1 offset=0 // CHECK-64-NEXT: (struct size=1 alignment=1 stride=1 num_extra_inhabitants=0 bitwise_takable=1 // CHECK-64-NEXT: (field name=_value offset=0 // CHECK-64-NEXT: (builtin size=1 alignment=1 stride=1 num_extra_inhabitants=0 bitwise_takable=1)))) // CHECK-64-NEXT: (field name=i2 offset=2 // CHECK-64-NEXT: (struct size=2 alignment=2 stride=2 num_extra_inhabitants=0 bitwise_takable=1 // CHECK-64-NEXT: (field name=_value offset=0 // CHECK-64-NEXT: (builtin size=2 alignment=2 stride=2 num_extra_inhabitants=0 bitwise_takable=1)))) // CHECK-64-NEXT: (field name=i3 offset=4 // CHECK-64-NEXT: (struct size=4 alignment=4 stride=4 num_extra_inhabitants=0 bitwise_takable=1 // CHECK-64-NEXT: (field name=_value offset=0 // CHECK-64-NEXT: (builtin size=4 alignment=4 stride=4 num_extra_inhabitants=0 bitwise_takable=1)))) // CHECK-64-NEXT: (field name=bi1 offset=8 // CHECK-64-NEXT: (struct size=1 alignment=1 stride=1 num_extra_inhabitants=0 bitwise_takable=1 // CHECK-64-NEXT: (field name=value offset=0 // CHECK-64-NEXT: (struct size=1 alignment=1 stride=1 num_extra_inhabitants=0 bitwise_takable=1 // CHECK-64-NEXT: (field name=_value offset=0 // CHECK-64-NEXT: (builtin size=1 alignment=1 stride=1 num_extra_inhabitants=0 bitwise_takable=1)))))) // CHECK-64-NEXT: (field name=bi2 offset=10 // CHECK-64-NEXT: (struct size=2 alignment=2 stride=2 num_extra_inhabitants=0 bitwise_takable=1 // CHECK-64-NEXT: (field name=value offset=0 // CHECK-64-NEXT: (struct size=2 alignment=2 stride=2 num_extra_inhabitants=0 bitwise_takable=1 // CHECK-64-NEXT: (field name=_value offset=0 // CHECK-64-NEXT: (builtin size=2 alignment=2 stride=2 num_extra_inhabitants=0 bitwise_takable=1)))))) // CHECK-64-NEXT: (field name=bi3 offset=12 // CHECK-64-NEXT: (struct size=4 alignment=4 stride=4 num_extra_inhabitants=0 bitwise_takable=1 // CHECK-64-NEXT: (field name=value offset=0 // CHECK-64-NEXT: (struct size=4 alignment=4 stride=4 num_extra_inhabitants=0 bitwise_takable=1 // CHECK-64-NEXT: (field name=_value offset=0 // CHECK-64-NEXT: (builtin size=4 alignment=4 stride=4 num_extra_inhabitants=0 bitwise_takable=1))))))) // CHECK-32: (struct TypeLowering.BasicStruct) // CHECK-32-NEXT: (struct size=16 alignment=4 stride=16 num_extra_inhabitants=0 bitwise_takable=1 // CHECK-32-NEXT: (field name=i1 offset=0 // CHECK-32-NEXT: (struct size=1 alignment=1 stride=1 num_extra_inhabitants=0 bitwise_takable=1 // CHECK-32-NEXT: (field name=_value offset=0 // CHECK-32-NEXT: (builtin size=1 alignment=1 stride=1 num_extra_inhabitants=0 bitwise_takable=1)))) // CHECK-32-NEXT: (field name=i2 offset=2 // CHECK-32-NEXT: (struct size=2 alignment=2 stride=2 num_extra_inhabitants=0 bitwise_takable=1 // CHECK-32-NEXT: (field name=_value offset=0 // CHECK-32-NEXT: (builtin size=2 alignment=2 stride=2 num_extra_inhabitants=0 bitwise_takable=1)))) // CHECK-32-NEXT: (field name=i3 offset=4 // CHECK-32-NEXT: (struct size=4 alignment=4 stride=4 num_extra_inhabitants=0 bitwise_takable=1 // CHECK-32-NEXT: (field name=_value offset=0 // CHECK-32-NEXT: (builtin size=4 alignment=4 stride=4 num_extra_inhabitants=0 bitwise_takable=1)))) // CHECK-32-NEXT: (field name=bi1 offset=8 // CHECK-32-NEXT: (struct size=1 alignment=1 stride=1 num_extra_inhabitants=0 bitwise_takable=1 // CHECK-32-NEXT: (field name=value offset=0 // CHECK-32-NEXT: (struct size=1 alignment=1 stride=1 num_extra_inhabitants=0 bitwise_takable=1 // CHECK-32-NEXT: (field name=_value offset=0 // CHECK-32-NEXT: (builtin size=1 alignment=1 stride=1 num_extra_inhabitants=0 bitwise_takable=1)))))) // CHECK-32-NEXT: (field name=bi2 offset=10 // CHECK-32-NEXT: (struct size=2 alignment=2 stride=2 num_extra_inhabitants=0 bitwise_takable=1 // CHECK-32-NEXT: (field name=value offset=0 // CHECK-32-NEXT: (struct size=2 alignment=2 stride=2 num_extra_inhabitants=0 bitwise_takable=1 // CHECK-32-NEXT: (field name=_value offset=0 // CHECK-32-NEXT: (builtin size=2 alignment=2 stride=2 num_extra_inhabitants=0 bitwise_takable=1)))))) // CHECK-32-NEXT: (field name=bi3 offset=12 // CHECK-32-NEXT: (struct size=4 alignment=4 stride=4 num_extra_inhabitants=0 bitwise_takable=1 // CHECK-32-NEXT: (field name=value offset=0 // CHECK-32-NEXT: (struct size=4 alignment=4 stride=4 num_extra_inhabitants=0 bitwise_takable=1 // CHECK-32-NEXT: (field name=_value offset=0 // CHECK-32-NEXT: (builtin size=4 alignment=4 stride=4 num_extra_inhabitants=0 bitwise_takable=1))))))) 12TypeLowering05AssocA6StructV // CHECK-64: (struct TypeLowering.AssocTypeStruct) // CHECK-64-NEXT: (struct size=36 alignment=2 stride=36 num_extra_inhabitants=0 bitwise_takable=1 // CHECK-64-NEXT: (field name=t1 offset=0 // CHECK-64-NEXT: (struct size=7 alignment=2 stride=8 num_extra_inhabitants=0 bitwise_takable=1 // CHECK-64-NEXT: (field name=a offset=0 // CHECK-64-NEXT: (struct size=2 alignment=2 stride=2 num_extra_inhabitants=0 bitwise_takable=1 // CHECK-64-NEXT: (field name=value offset=0 // CHECK-64-NEXT: (struct size=2 alignment=2 stride=2 num_extra_inhabitants=0 bitwise_takable=1 // CHECK-64-NEXT: (field name=_value offset=0 // CHECK-64-NEXT: (builtin size=2 alignment=2 stride=2 num_extra_inhabitants=0 bitwise_takable=1)))))) // CHECK-64-NEXT: (field name=b offset=2 // CHECK-64-NEXT: (struct size=1 alignment=1 stride=1 num_extra_inhabitants=0 bitwise_takable=1 // CHECK-64-NEXT: (field name=value offset=0 // CHECK-64-NEXT: (struct size=1 alignment=1 stride=1 num_extra_inhabitants=0 bitwise_takable=1 // CHECK-64-NEXT: (field name=_value offset=0 // CHECK-64-NEXT: (builtin size=1 alignment=1 stride=1 num_extra_inhabitants=0 bitwise_takable=1)))))) // CHECK-64-NEXT: (field name=c offset=4 // CHECK-64-NEXT: (tuple size=3 alignment=2 stride=4 num_extra_inhabitants=0 bitwise_takable=1 // CHECK-64-NEXT: (field offset=0 // CHECK-64-NEXT: (struct size=2 alignment=2 stride=2 num_extra_inhabitants=0 bitwise_takable=1 // CHECK-64-NEXT: (field name=value offset=0 // CHECK-64-NEXT: (struct size=2 alignment=2 stride=2 num_extra_inhabitants=0 bitwise_takable=1 // CHECK-64-NEXT: (field name=_value offset=0 // CHECK-64-NEXT: (builtin size=2 alignment=2 stride=2 num_extra_inhabitants=0 bitwise_takable=1)))))) // CHECK-64-NEXT: (field offset=2 // CHECK-64-NEXT: (struct size=1 alignment=1 stride=1 num_extra_inhabitants=0 bitwise_takable=1 // CHECK-64-NEXT: (field name=value offset=0 // CHECK-64-NEXT: (struct size=1 alignment=1 stride=1 num_extra_inhabitants=0 bitwise_takable=1 // CHECK-64-NEXT: (field name=_value offset=0 // CHECK-64-NEXT: (builtin size=1 alignment=1 stride=1 num_extra_inhabitants=0 bitwise_takable=1)))))))))) // CHECK-64-NEXT: (field name=t2 offset=8 // CHECK-64-NEXT: (struct size=7 alignment=2 stride=8 num_extra_inhabitants=0 bitwise_takable=1 // CHECK-64-NEXT: (field name=a offset=0 // CHECK-64-NEXT: (struct size=2 alignment=2 stride=2 num_extra_inhabitants=0 bitwise_takable=1 // CHECK-64-NEXT: (field name=value offset=0 // CHECK-64-NEXT: (struct size=2 alignment=2 stride=2 num_extra_inhabitants=0 bitwise_takable=1 // CHECK-64-NEXT: (field name=_value offset=0 // CHECK-64-NEXT: (builtin size=2 alignment=2 stride=2 num_extra_inhabitants=0 bitwise_takable=1)))))) // CHECK-64-NEXT: (field name=b offset=2 // CHECK-64-NEXT: (struct size=1 alignment=1 stride=1 num_extra_inhabitants=0 bitwise_takable=1 // CHECK-64-NEXT: (field name=value offset=0 // CHECK-64-NEXT: (struct size=1 alignment=1 stride=1 num_extra_inhabitants=0 bitwise_takable=1 // CHECK-64-NEXT: (field name=_value offset=0 // CHECK-64-NEXT: (builtin size=1 alignment=1 stride=1 num_extra_inhabitants=0 bitwise_takable=1)))))) // CHECK-64-NEXT: (field name=c offset=4 // CHECK-64-NEXT: (tuple size=3 alignment=2 stride=4 num_extra_inhabitants=0 bitwise_takable=1 // CHECK-64-NEXT: (field offset=0 // CHECK-64-NEXT: (struct size=2 alignment=2 stride=2 num_extra_inhabitants=0 bitwise_takable=1 // CHECK-64-NEXT: (field name=value offset=0 // CHECK-64-NEXT: (struct size=2 alignment=2 stride=2 num_extra_inhabitants=0 bitwise_takable=1 // CHECK-64-NEXT: (field name=_value offset=0 // CHECK-64-NEXT: (builtin size=2 alignment=2 stride=2 num_extra_inhabitants=0 bitwise_takable=1)))))) // CHECK-64-NEXT: (field offset=2 // CHECK-64-NEXT: (struct size=1 alignment=1 stride=1 num_extra_inhabitants=0 bitwise_takable=1 // CHECK-64-NEXT: (field name=value offset=0 // CHECK-64-NEXT: (struct size=1 alignment=1 stride=1 num_extra_inhabitants=0 bitwise_takable=1 // CHECK-64-NEXT: (field name=_value offset=0 // CHECK-64-NEXT: (builtin size=1 alignment=1 stride=1 num_extra_inhabitants=0 bitwise_takable=1)))))))))) // CHECK-64-NEXT: (field name=t3 offset=16 // CHECK-64-NEXT: (struct size=8 alignment=2 stride=8 num_extra_inhabitants=0 bitwise_takable=1 // CHECK-64-NEXT: (field name=a offset=0 // CHECK-64-NEXT: (struct size=1 alignment=1 stride=1 num_extra_inhabitants=0 bitwise_takable=1 // CHECK-64-NEXT: (field name=value offset=0 // CHECK-64-NEXT: (struct size=1 alignment=1 stride=1 num_extra_inhabitants=0 bitwise_takable=1 // CHECK-64-NEXT: (field name=_value offset=0 // CHECK-64-NEXT: (builtin size=1 alignment=1 stride=1 num_extra_inhabitants=0 bitwise_takable=1)))))) // CHECK-64-NEXT: (field name=b offset=2 // CHECK-64-NEXT: (struct size=2 alignment=2 stride=2 num_extra_inhabitants=0 bitwise_takable=1 // CHECK-64-NEXT: (field name=value offset=0 // CHECK-64-NEXT: (struct size=2 alignment=2 stride=2 num_extra_inhabitants=0 bitwise_takable=1 // CHECK-64-NEXT: (field name=_value offset=0 // CHECK-64-NEXT: (builtin size=2 alignment=2 stride=2 num_extra_inhabitants=0 bitwise_takable=1)))))) // CHECK-64-NEXT: (field name=c offset=4 // CHECK-64-NEXT: (tuple size=4 alignment=2 stride=4 num_extra_inhabitants=0 bitwise_takable=1 // CHECK-64-NEXT: (field offset=0 // CHECK-64-NEXT: (struct size=1 alignment=1 stride=1 num_extra_inhabitants=0 bitwise_takable=1 // CHECK-64-NEXT: (field name=value offset=0 // CHECK-64-NEXT: (struct size=1 alignment=1 stride=1 num_extra_inhabitants=0 bitwise_takable=1 // CHECK-64-NEXT: (field name=_value offset=0 // CHECK-64-NEXT: (builtin size=1 alignment=1 stride=1 num_extra_inhabitants=0 bitwise_takable=1)))))) // CHECK-64-NEXT: (field offset=2 // CHECK-64-NEXT: (struct size=2 alignment=2 stride=2 num_extra_inhabitants=0 bitwise_takable=1 // CHECK-64-NEXT: (field name=value offset=0 // CHECK-64-NEXT: (struct size=2 alignment=2 stride=2 num_extra_inhabitants=0 bitwise_takable=1 // CHECK-64-NEXT: (field name=_value offset=0 // CHECK-64-NEXT: (builtin size=2 alignment=2 stride=2 num_extra_inhabitants=0 bitwise_takable=1)))))))))) // CHECK-64-NEXT: (field name=t4 offset=24 // CHECK-64-NEXT: (struct size=8 alignment=2 stride=8 num_extra_inhabitants=0 bitwise_takable=1 // CHECK-64-NEXT: (field name=a offset=0 // CHECK-64-NEXT: (struct size=1 alignment=1 stride=1 num_extra_inhabitants=0 bitwise_takable=1 // CHECK-64-NEXT: (field name=value offset=0 // CHECK-64-NEXT: (struct size=1 alignment=1 stride=1 num_extra_inhabitants=0 bitwise_takable=1 // CHECK-64-NEXT: (field name=_value offset=0 // CHECK-64-NEXT: (builtin size=1 alignment=1 stride=1 num_extra_inhabitants=0 bitwise_takable=1)))))) // CHECK-64-NEXT: (field name=b offset=2 // CHECK-64-NEXT: (struct size=2 alignment=2 stride=2 num_extra_inhabitants=0 bitwise_takable=1 // CHECK-64-NEXT: (field name=value offset=0 // CHECK-64-NEXT: (struct size=2 alignment=2 stride=2 num_extra_inhabitants=0 bitwise_takable=1 // CHECK-64-NEXT: (field name=_value offset=0 // CHECK-64-NEXT: (builtin size=2 alignment=2 stride=2 num_extra_inhabitants=0 bitwise_takable=1)))))) // CHECK-64-NEXT: (field name=c offset=4 // CHECK-64-NEXT: (tuple size=4 alignment=2 stride=4 num_extra_inhabitants=0 bitwise_takable=1 // CHECK-64-NEXT: (field offset=0 // CHECK-64-NEXT: (struct size=1 alignment=1 stride=1 num_extra_inhabitants=0 bitwise_takable=1 // CHECK-64-NEXT: (field name=value offset=0 // CHECK-64-NEXT: (struct size=1 alignment=1 stride=1 num_extra_inhabitants=0 bitwise_takable=1 // CHECK-64-NEXT: (field name=_value offset=0 // CHECK-64-NEXT: (builtin size=1 alignment=1 stride=1 num_extra_inhabitants=0 bitwise_takable=1)))))) // CHECK-64-NEXT: (field offset=2 // CHECK-64-NEXT: (struct size=2 alignment=2 stride=2 num_extra_inhabitants=0 bitwise_takable=1 // CHECK-64-NEXT: (field name=value offset=0 // CHECK-64-NEXT: (struct size=2 alignment=2 stride=2 num_extra_inhabitants=0 bitwise_takable=1 // CHECK-64-NEXT: (field name=_value offset=0 // CHECK-64-NEXT: (builtin size=2 alignment=2 stride=2 num_extra_inhabitants=0 bitwise_takable=1)))))))))) // CHECK-64-NEXT: (field name=t5 offset=32 // CHECK-64-NEXT: (struct size=4 alignment=1 stride=4 num_extra_inhabitants=0 bitwise_takable=1 // CHECK-64-NEXT: (field name=a offset=0 // CHECK-64-NEXT: (struct size=1 alignment=1 stride=1 num_extra_inhabitants=0 bitwise_takable=1 // CHECK-64-NEXT: (field name=value offset=0 // CHECK-64-NEXT: (struct size=1 alignment=1 stride=1 num_extra_inhabitants=0 bitwise_takable=1 // CHECK-64-NEXT: (field name=_value offset=0 // CHECK-64-NEXT: (builtin size=1 alignment=1 stride=1 num_extra_inhabitants=0 bitwise_takable=1)))))) // CHECK-64-NEXT: (field name=b offset=1 // CHECK-64-NEXT: (struct size=1 alignment=1 stride=1 num_extra_inhabitants=0 bitwise_takable=1 // CHECK-64-NEXT: (field name=value offset=0 // CHECK-64-NEXT: (struct size=1 alignment=1 stride=1 num_extra_inhabitants=0 bitwise_takable=1 // CHECK-64-NEXT: (field name=_value offset=0 // CHECK-64-NEXT: (builtin size=1 alignment=1 stride=1 num_extra_inhabitants=0 bitwise_takable=1)))))) // CHECK-64-NEXT: (field name=c offset=2 // CHECK-64-NEXT: (tuple size=2 alignment=1 stride=2 num_extra_inhabitants=0 bitwise_takable=1 // CHECK-64-NEXT: (field offset=0 // CHECK-64-NEXT: (struct size=1 alignment=1 stride=1 num_extra_inhabitants=0 bitwise_takable=1 // CHECK-64-NEXT: (field name=value offset=0 // CHECK-64-NEXT: (struct size=1 alignment=1 stride=1 num_extra_inhabitants=0 bitwise_takable=1 // CHECK-64-NEXT: (field name=_value offset=0 // CHECK-64-NEXT: (builtin size=1 alignment=1 stride=1 num_extra_inhabitants=0 bitwise_takable=1)))))) // CHECK-64-NEXT: (field offset=1 // CHECK-64-NEXT: (struct size=1 alignment=1 stride=1 num_extra_inhabitants=0 bitwise_takable=1 // CHECK-64-NEXT: (field name=value offset=0 // CHECK-64-NEXT: (struct size=1 alignment=1 stride=1 num_extra_inhabitants=0 bitwise_takable=1 // CHECK-64-NEXT: (field name=_value offset=0 // CHECK-64-NEXT: (builtin size=1 alignment=1 stride=1 num_extra_inhabitants=0 bitwise_takable=1))))))))))) // CHECK-32: (struct TypeLowering.AssocTypeStruct) // CHECK-32-NEXT: (struct size=36 alignment=2 stride=36 num_extra_inhabitants=0 bitwise_takable=1 // CHECK-32-NEXT: (field name=t1 offset=0 // CHECK-32-NEXT: (struct size=7 alignment=2 stride=8 num_extra_inhabitants=0 bitwise_takable=1 // CHECK-32-NEXT: (field name=a offset=0 // CHECK-32-NEXT: (struct size=2 alignment=2 stride=2 num_extra_inhabitants=0 bitwise_takable=1 // CHECK-32-NEXT: (field name=value offset=0 // CHECK-32-NEXT: (struct size=2 alignment=2 stride=2 num_extra_inhabitants=0 bitwise_takable=1 // CHECK-32-NEXT: (field name=_value offset=0 // CHECK-32-NEXT: (builtin size=2 alignment=2 stride=2 num_extra_inhabitants=0 bitwise_takable=1)))))) // CHECK-32-NEXT: (field name=b offset=2 // CHECK-32-NEXT: (struct size=1 alignment=1 stride=1 num_extra_inhabitants=0 bitwise_takable=1 // CHECK-32-NEXT: (field name=value offset=0 // CHECK-32-NEXT: (struct size=1 alignment=1 stride=1 num_extra_inhabitants=0 bitwise_takable=1 // CHECK-32-NEXT: (field name=_value offset=0 // CHECK-32-NEXT: (builtin size=1 alignment=1 stride=1 num_extra_inhabitants=0 bitwise_takable=1)))))) // CHECK-32-NEXT: (field name=c offset=4 // CHECK-32-NEXT: (tuple size=3 alignment=2 stride=4 num_extra_inhabitants=0 bitwise_takable=1 // CHECK-32-NEXT: (field offset=0 // CHECK-32-NEXT: (struct size=2 alignment=2 stride=2 num_extra_inhabitants=0 bitwise_takable=1 // CHECK-32-NEXT: (field name=value offset=0 // CHECK-32-NEXT: (struct size=2 alignment=2 stride=2 num_extra_inhabitants=0 bitwise_takable=1 // CHECK-32-NEXT: (field name=_value offset=0 // CHECK-32-NEXT: (builtin size=2 alignment=2 stride=2 num_extra_inhabitants=0 bitwise_takable=1)))))) // CHECK-32-NEXT: (field offset=2 // CHECK-32-NEXT: (struct size=1 alignment=1 stride=1 num_extra_inhabitants=0 bitwise_takable=1 // CHECK-32-NEXT: (field name=value offset=0 // CHECK-32-NEXT: (struct size=1 alignment=1 stride=1 num_extra_inhabitants=0 bitwise_takable=1 // CHECK-32-NEXT: (field name=_value offset=0 // CHECK-32-NEXT: (builtin size=1 alignment=1 stride=1 num_extra_inhabitants=0 bitwise_takable=1)))))))))) // CHECK-32-NEXT: (field name=t2 offset=8 // CHECK-32-NEXT: (struct size=7 alignment=2 stride=8 num_extra_inhabitants=0 bitwise_takable=1 // CHECK-32-NEXT: (field name=a offset=0 // CHECK-32-NEXT: (struct size=2 alignment=2 stride=2 num_extra_inhabitants=0 bitwise_takable=1 // CHECK-32-NEXT: (field name=value offset=0 // CHECK-32-NEXT: (struct size=2 alignment=2 stride=2 num_extra_inhabitants=0 bitwise_takable=1 // CHECK-32-NEXT: (field name=_value offset=0 // CHECK-32-NEXT: (builtin size=2 alignment=2 stride=2 num_extra_inhabitants=0 bitwise_takable=1)))))) // CHECK-32-NEXT: (field name=b offset=2 // CHECK-32-NEXT: (struct size=1 alignment=1 stride=1 num_extra_inhabitants=0 bitwise_takable=1 // CHECK-32-NEXT: (field name=value offset=0 // CHECK-32-NEXT: (struct size=1 alignment=1 stride=1 num_extra_inhabitants=0 bitwise_takable=1 // CHECK-32-NEXT: (field name=_value offset=0 // CHECK-32-NEXT: (builtin size=1 alignment=1 stride=1 num_extra_inhabitants=0 bitwise_takable=1)))))) // CHECK-32-NEXT: (field name=c offset=4 // CHECK-32-NEXT: (tuple size=3 alignment=2 stride=4 num_extra_inhabitants=0 bitwise_takable=1 // CHECK-32-NEXT: (field offset=0 // CHECK-32-NEXT: (struct size=2 alignment=2 stride=2 num_extra_inhabitants=0 bitwise_takable=1 // CHECK-32-NEXT: (field name=value offset=0 // CHECK-32-NEXT: (struct size=2 alignment=2 stride=2 num_extra_inhabitants=0 bitwise_takable=1 // CHECK-32-NEXT: (field name=_value offset=0 // CHECK-32-NEXT: (builtin size=2 alignment=2 stride=2 num_extra_inhabitants=0 bitwise_takable=1)))))) // CHECK-32-NEXT: (field offset=2 // CHECK-32-NEXT: (struct size=1 alignment=1 stride=1 num_extra_inhabitants=0 bitwise_takable=1 // CHECK-32-NEXT: (field name=value offset=0 // CHECK-32-NEXT: (struct size=1 alignment=1 stride=1 num_extra_inhabitants=0 bitwise_takable=1 // CHECK-32-NEXT: (field name=_value offset=0 // CHECK-32-NEXT: (builtin size=1 alignment=1 stride=1 num_extra_inhabitants=0 bitwise_takable=1)))))))))) // CHECK-32-NEXT: (field name=t3 offset=16 // CHECK-32-NEXT: (struct size=8 alignment=2 stride=8 num_extra_inhabitants=0 bitwise_takable=1 // CHECK-32-NEXT: (field name=a offset=0 // CHECK-32-NEXT: (struct size=1 alignment=1 stride=1 num_extra_inhabitants=0 bitwise_takable=1 // CHECK-32-NEXT: (field name=value offset=0 // CHECK-32-NEXT: (struct size=1 alignment=1 stride=1 num_extra_inhabitants=0 bitwise_takable=1 // CHECK-32-NEXT: (field name=_value offset=0 // CHECK-32-NEXT: (builtin size=1 alignment=1 stride=1 num_extra_inhabitants=0 bitwise_takable=1)))))) // CHECK-32-NEXT: (field name=b offset=2 // CHECK-32-NEXT: (struct size=2 alignment=2 stride=2 num_extra_inhabitants=0 bitwise_takable=1 // CHECK-32-NEXT: (field name=value offset=0 // CHECK-32-NEXT: (struct size=2 alignment=2 stride=2 num_extra_inhabitants=0 bitwise_takable=1 // CHECK-32-NEXT: (field name=_value offset=0 // CHECK-32-NEXT: (builtin size=2 alignment=2 stride=2 num_extra_inhabitants=0 bitwise_takable=1)))))) // CHECK-32-NEXT: (field name=c offset=4 // CHECK-32-NEXT: (tuple size=4 alignment=2 stride=4 num_extra_inhabitants=0 bitwise_takable=1 // CHECK-32-NEXT: (field offset=0 // CHECK-32-NEXT: (struct size=1 alignment=1 stride=1 num_extra_inhabitants=0 bitwise_takable=1 // CHECK-32-NEXT: (field name=value offset=0 // CHECK-32-NEXT: (struct size=1 alignment=1 stride=1 num_extra_inhabitants=0 bitwise_takable=1 // CHECK-32-NEXT: (field name=_value offset=0 // CHECK-32-NEXT: (builtin size=1 alignment=1 stride=1 num_extra_inhabitants=0 bitwise_takable=1)))))) // CHECK-32-NEXT: (field offset=2 // CHECK-32-NEXT: (struct size=2 alignment=2 stride=2 num_extra_inhabitants=0 bitwise_takable=1 // CHECK-32-NEXT: (field name=value offset=0 // CHECK-32-NEXT: (struct size=2 alignment=2 stride=2 num_extra_inhabitants=0 bitwise_takable=1 // CHECK-32-NEXT: (field name=_value offset=0 // CHECK-32-NEXT: (builtin size=2 alignment=2 stride=2 num_extra_inhabitants=0 bitwise_takable=1)))))))))) // CHECK-32-NEXT: (field name=t4 offset=24 // CHECK-32-NEXT: (struct size=8 alignment=2 stride=8 num_extra_inhabitants=0 bitwise_takable=1 // CHECK-32-NEXT: (field name=a offset=0 // CHECK-32-NEXT: (struct size=1 alignment=1 stride=1 num_extra_inhabitants=0 bitwise_takable=1 // CHECK-32-NEXT: (field name=value offset=0 // CHECK-32-NEXT: (struct size=1 alignment=1 stride=1 num_extra_inhabitants=0 bitwise_takable=1 // CHECK-32-NEXT: (field name=_value offset=0 // CHECK-32-NEXT: (builtin size=1 alignment=1 stride=1 num_extra_inhabitants=0 bitwise_takable=1)))))) // CHECK-32-NEXT: (field name=b offset=2 // CHECK-32-NEXT: (struct size=2 alignment=2 stride=2 num_extra_inhabitants=0 bitwise_takable=1 // CHECK-32-NEXT: (field name=value offset=0 // CHECK-32-NEXT: (struct size=2 alignment=2 stride=2 num_extra_inhabitants=0 bitwise_takable=1 // CHECK-32-NEXT: (field name=_value offset=0 // CHECK-32-NEXT: (builtin size=2 alignment=2 stride=2 num_extra_inhabitants=0 bitwise_takable=1)))))) // CHECK-32-NEXT: (field name=c offset=4 // CHECK-32-NEXT: (tuple size=4 alignment=2 stride=4 num_extra_inhabitants=0 bitwise_takable=1 // CHECK-32-NEXT: (field offset=0 // CHECK-32-NEXT: (struct size=1 alignment=1 stride=1 num_extra_inhabitants=0 bitwise_takable=1 // CHECK-32-NEXT: (field name=value offset=0 // CHECK-32-NEXT: (struct size=1 alignment=1 stride=1 num_extra_inhabitants=0 bitwise_takable=1 // CHECK-32-NEXT: (field name=_value offset=0 // CHECK-32-NEXT: (builtin size=1 alignment=1 stride=1 num_extra_inhabitants=0 bitwise_takable=1)))))) // CHECK-32-NEXT: (field offset=2 // CHECK-32-NEXT: (struct size=2 alignment=2 stride=2 num_extra_inhabitants=0 bitwise_takable=1 // CHECK-32-NEXT: (field name=value offset=0 // CHECK-32-NEXT: (struct size=2 alignment=2 stride=2 num_extra_inhabitants=0 bitwise_takable=1 // CHECK-32-NEXT: (field name=_value offset=0 // CHECK-32-NEXT: (builtin size=2 alignment=2 stride=2 num_extra_inhabitants=0 bitwise_takable=1)))))))))) // CHECK-32-NEXT: (field name=t5 offset=32 // CHECK-32-NEXT: (struct size=4 alignment=1 stride=4 num_extra_inhabitants=0 bitwise_takable=1 // CHECK-32-NEXT: (field name=a offset=0 // CHECK-32-NEXT: (struct size=1 alignment=1 stride=1 num_extra_inhabitants=0 bitwise_takable=1 // CHECK-32-NEXT: (field name=value offset=0 // CHECK-32-NEXT: (struct size=1 alignment=1 stride=1 num_extra_inhabitants=0 bitwise_takable=1 // CHECK-32-NEXT: (field name=_value offset=0 // CHECK-32-NEXT: (builtin size=1 alignment=1 stride=1 num_extra_inhabitants=0 bitwise_takable=1)))))) // CHECK-32-NEXT: (field name=b offset=1 // CHECK-32-NEXT: (struct size=1 alignment=1 stride=1 num_extra_inhabitants=0 bitwise_takable=1 // CHECK-32-NEXT: (field name=value offset=0 // CHECK-32-NEXT: (struct size=1 alignment=1 stride=1 num_extra_inhabitants=0 bitwise_takable=1 // CHECK-32-NEXT: (field name=_value offset=0 // CHECK-32-NEXT: (builtin size=1 alignment=1 stride=1 num_extra_inhabitants=0 bitwise_takable=1)))))) // CHECK-32-NEXT: (field name=c offset=2 // CHECK-32-NEXT: (tuple size=2 alignment=1 stride=2 num_extra_inhabitants=0 bitwise_takable=1 // CHECK-32-NEXT: (field offset=0 // CHECK-32-NEXT: (struct size=1 alignment=1 stride=1 num_extra_inhabitants=0 bitwise_takable=1 // CHECK-32-NEXT: (field name=value offset=0 // CHECK-32-NEXT: (struct size=1 alignment=1 stride=1 num_extra_inhabitants=0 bitwise_takable=1 // CHECK-32-NEXT: (field name=_value offset=0 // CHECK-32-NEXT: (builtin size=1 alignment=1 stride=1 num_extra_inhabitants=0 bitwise_takable=1)))))) // CHECK-32-NEXT: (field offset=1 // CHECK-32-NEXT: (struct size=1 alignment=1 stride=1 num_extra_inhabitants=0 bitwise_takable=1 // CHECK-32-NEXT: (field name=value offset=0 // CHECK-32-NEXT: (struct size=1 alignment=1 stride=1 num_extra_inhabitants=0 bitwise_takable=1 // CHECK-32-NEXT: (field name=_value offset=0 // CHECK-32-NEXT: (builtin size=1 alignment=1 stride=1 num_extra_inhabitants=0 bitwise_takable=1))))))))))) 12TypeLowering3BoxVys5Int16VG_s5Int32Vt // CHECK-64-NEXT: (tuple // CHECK-64-NEXT: (bound_generic_struct TypeLowering.Box // CHECK-64-NEXT: (struct Swift.Int16)) // CHECK-64-NEXT: (struct Swift.Int32)) // CHECK-32-NEXT: (tuple // CHECK-32-NEXT: (bound_generic_struct TypeLowering.Box // CHECK-32-NEXT: (struct Swift.Int16)) // CHECK-32-NEXT: (struct Swift.Int32)) // CHECK-64-NEXT: (tuple size=8 alignment=4 stride=8 num_extra_inhabitants=0 bitwise_takable=1 // CHECK-64-NEXT: (field offset=0 // CHECK-64-NEXT: (struct size=2 alignment=2 stride=2 num_extra_inhabitants=0 bitwise_takable=1 // CHECK-64-NEXT: (field name=value offset=0 // CHECK-64-NEXT: (struct size=2 alignment=2 stride=2 num_extra_inhabitants=0 bitwise_takable=1 // CHECK-64-NEXT: (field name=_value offset=0 // CHECK-64-NEXT: (builtin size=2 alignment=2 stride=2 num_extra_inhabitants=0 bitwise_takable=1)))))) // CHECK-64-NEXT: (field offset=4 // CHECK-64-NEXT: (struct size=4 alignment=4 stride=4 num_extra_inhabitants=0 bitwise_takable=1 // CHECK-64-NEXT: (field name=_value offset=0 // CHECK-64-NEXT: (builtin size=4 alignment=4 stride=4 num_extra_inhabitants=0 bitwise_takable=1))))) // CHECK-32-NEXT: (tuple size=8 alignment=4 stride=8 num_extra_inhabitants=0 bitwise_takable=1 // CHECK-32-NEXT: (field offset=0 // CHECK-32-NEXT: (struct size=2 alignment=2 stride=2 num_extra_inhabitants=0 bitwise_takable=1 // CHECK-32-NEXT: (field name=value offset=0 // CHECK-32-NEXT: (struct size=2 alignment=2 stride=2 num_extra_inhabitants=0 bitwise_takable=1 // CHECK-32-NEXT: (field name=_value offset=0 // CHECK-32-NEXT: (builtin size=2 alignment=2 stride=2 num_extra_inhabitants=0 bitwise_takable=1)))))) // CHECK-32-NEXT: (field offset=4 // CHECK-32-NEXT: (struct size=4 alignment=4 stride=4 num_extra_inhabitants=0 bitwise_takable=1 // CHECK-32-NEXT: (field name=_value offset=0 // CHECK-32-NEXT: (builtin size=4 alignment=4 stride=4 num_extra_inhabitants=0 bitwise_takable=1))))) 12TypeLowering15ReferenceStructV // CHECK-64: (struct TypeLowering.ReferenceStruct) // CHECK-64-NEXT: (struct size=48 alignment=8 stride=48 num_extra_inhabitants=[[PTR_XI:2048|4096|2147483647]] bitwise_takable=1 // CHECK-64-NEXT: (field name=strongRef offset=0 // CHECK-64-NEXT: (reference kind=strong refcounting=native)) // CHECK-64-NEXT: (field name=optionalStrongRef offset=8 // CHECK-64-NEXT: (single_payload_enum size=8 alignment=8 stride=8 num_extra_inhabitants=[[PTR_XI_SUB_1:2047|4095|2147483646]] bitwise_takable=1 // CHECK-64-NEXT: (case name=some index=0 offset=0 // CHECK-64-NEXT: (reference kind=strong refcounting=native)) // CHECK-64-NEXT: (case name=none index=1))) // CHECK-64-NEXT: (field name=strongRefTuple offset=16 // CHECK-64-NEXT: (tuple size=16 alignment=8 stride=16 num_extra_inhabitants=[[PTR_XI]] bitwise_takable=1 // CHECK-64-NEXT: (field offset=0 // CHECK-64-NEXT: (reference kind=strong refcounting=native)) // CHECK-64-NEXT: (field offset=8 // CHECK-64-NEXT: (reference kind=strong refcounting=native)))) // CHECK-64-NEXT: (field name=optionalStrongRefTuple offset=32 // CHECK-64-NEXT: (single_payload_enum size=16 alignment=8 stride=16 num_extra_inhabitants=[[PTR_XI_SUB_1]] bitwise_takable=1 // CHECK-64-NEXT: (case name=some index=0 offset=0 // CHECK-64-NEXT: (tuple size=16 alignment=8 stride=16 num_extra_inhabitants=[[PTR_XI]] bitwise_takable=1 // CHECK-64-NEXT: (field offset=0 // CHECK-64-NEXT: (reference kind=strong refcounting=native)) // CHECK-64-NEXT: (field offset=8 // CHECK-64-NEXT: (reference kind=strong refcounting=native)))) // CHECK-64-NEXT: (case name=none index=1)))) // CHECK-32: (struct TypeLowering.ReferenceStruct) // CHECK-32-NEXT: (struct size=24 alignment=4 stride=24 num_extra_inhabitants=4096 bitwise_takable=1 // CHECK-32-NEXT: (field name=strongRef offset=0 // CHECK-32-NEXT: (reference kind=strong refcounting=native)) // CHECK-32-NEXT: (field name=optionalStrongRef offset=4 // CHECK-32-NEXT: (single_payload_enum size=4 alignment=4 stride=4 num_extra_inhabitants=4095 bitwise_takable=1 // CHECK-32-NEXT: (case name=some index=0 offset=0 // CHECK-32-NEXT: (reference kind=strong refcounting=native)) // CHECK-32-NEXT: (case name=none index=1))) // CHECK-32-NEXT: (field name=strongRefTuple offset=8 // CHECK-32-NEXT: (tuple size=8 alignment=4 stride=8 num_extra_inhabitants=4096 bitwise_takable=1 // CHECK-32-NEXT: (field offset=0 // CHECK-32-NEXT: (reference kind=strong refcounting=native)) // CHECK-32-NEXT: (field offset=4 // CHECK-32-NEXT: (reference kind=strong refcounting=native)))) // CHECK-32-NEXT: (field name=optionalStrongRefTuple offset=16 // CHECK-32-NEXT: (single_payload_enum size=8 alignment=4 stride=8 num_extra_inhabitants=4095 bitwise_takable=1 // CHECK-32-NEXT: (case name=some index=0 offset=0 // CHECK-32-NEXT: (tuple size=8 alignment=4 stride=8 num_extra_inhabitants=4096 bitwise_takable=1 // CHECK-32-NEXT: (field offset=0 // CHECK-32-NEXT: (reference kind=strong refcounting=native)) // CHECK-32-NEXT: (field offset=4 // CHECK-32-NEXT: (reference kind=strong refcounting=native)))) // CHECK-32-NEXT: (case name=none index=1)))) 12TypeLowering22UnownedReferenceStructV // CHECK-64: (struct TypeLowering.UnownedReferenceStruct) // CHECK-64-NEXT: (struct size=8 alignment=8 stride=8 num_extra_inhabitants=[[PTR_XI]] bitwise_takable=1 // CHECK-64-NEXT: (field name=unownedRef offset=0 // CHECK-64-NEXT: (reference kind=unowned refcounting=native))) // CHECK-32: (struct TypeLowering.UnownedReferenceStruct) // CHECK-32-NEXT: (struct size=4 alignment=4 stride=4 num_extra_inhabitants=4096 bitwise_takable=1 // CHECK-32-NEXT: (field name=unownedRef offset=0 // CHECK-32-NEXT: (reference kind=unowned refcounting=native))) 12TypeLowering19WeakReferenceStructV // CHECK-64: (struct TypeLowering.WeakReferenceStruct) // CHECK-64-NEXT: (struct size=8 alignment=8 stride=8 num_extra_inhabitants=0 bitwise_takable=0 // CHECK-64-NEXT: (field name=weakRef offset=0 // CHECK-64-NEXT: (reference kind=weak refcounting=native))) // CHECK-32: (struct TypeLowering.WeakReferenceStruct) // CHECK-32-NEXT: (struct size=4 alignment=4 stride=4 num_extra_inhabitants=0 bitwise_takable=0 // CHECK-32-NEXT: (field name=weakRef offset=0 // CHECK-32-NEXT: (reference kind=weak refcounting=native))) 12TypeLowering24UnmanagedReferenceStructV // CHECK-64: (struct TypeLowering.UnmanagedReferenceStruct) // CHECK-64-NEXT: (struct size=8 alignment=8 stride=8 num_extra_inhabitants=[[PTR_XI]] bitwise_takable=1 // CHECK-64-NEXT: (field name=unmanagedRef offset=0 // CHECK-64-NEXT: (reference kind=unmanaged refcounting=native))) // CHECK-32: (struct TypeLowering.UnmanagedReferenceStruct) // CHECK-32-NEXT: (struct size=4 alignment=4 stride=4 num_extra_inhabitants=4096 bitwise_takable=1 // CHECK-32-NEXT: (field name=unmanagedRef offset=0 // CHECK-32-NEXT: (reference kind=unmanaged refcounting=native))) 12TypeLowering14FunctionStructV // CHECK-64: (struct TypeLowering.FunctionStruct) // CHECK-64-NEXT: (struct size=64 alignment=8 stride=64 num_extra_inhabitants=[[PTR_XI_2:4096|2147483647]] bitwise_takable=1 // CHECK-64-NEXT: (field name=thickFunction offset=0 // CHECK-64-NEXT: (thick_function size=16 alignment=8 stride=16 num_extra_inhabitants=[[PTR_XI_2]] bitwise_takable=1 // CHECK-64-NEXT: (field name=function offset=0 // CHECK-64-NEXT: (builtin size=8 alignment=8 stride=8 num_extra_inhabitants=[[PTR_XI_2]] bitwise_takable=1)) // CHECK-64-NEXT: (field name=context offset=8 // CHECK-64-NEXT: (reference kind=strong refcounting=native)))) // CHECK-64-NEXT: (field name=optionalThickFunction offset=16 // CHECK-64-NEXT: (single_payload_enum size=16 alignment=8 stride=16 num_extra_inhabitants=[[PTR_XI_2_SUB_1:4095|2147483646]] bitwise_takable=1 // CHECK-64-NEXT: (case name=some index=0 offset=0 // CHECK-64-NEXT: (thick_function size=16 alignment=8 stride=16 num_extra_inhabitants=[[PTR_XI_2]] bitwise_takable=1 // CHECK-64-NEXT: (field name=function offset=0 // CHECK-64-NEXT: (builtin size=8 alignment=8 stride=8 num_extra_inhabitants=[[PTR_XI_2]] bitwise_takable=1)) // CHECK-64-NEXT: (field name=context offset=8 // CHECK-64-NEXT: (reference kind=strong refcounting=native)))) // CHECK-64-NEXT: (case name=none index=1))) // CHECK-64-NEXT: (field name=thinFunction offset=32 // CHECK-64-NEXT: (builtin size=8 alignment=8 stride=8 num_extra_inhabitants=[[PTR_XI_2]] bitwise_takable=1)) // CHECK-64-NEXT: (field name=optionalThinFunction offset=40 // CHECK-64-NEXT: (single_payload_enum size=8 alignment=8 stride=8 num_extra_inhabitants=[[PTR_XI_2_SUB_1]] bitwise_takable=1 // CHECK-64-NEXT: (case name=some index=0 offset=0 // CHECK-64-NEXT: (builtin size=8 alignment=8 stride=8 num_extra_inhabitants=[[PTR_XI_2]] bitwise_takable=1)) // CHECK-64-NEXT: (case name=none index=1))) // CHECK-64-NEXT: (field name=cFunction offset=48 // CHECK-64-NEXT: (builtin size=8 alignment=8 stride=8 num_extra_inhabitants=[[PTR_XI_2]] bitwise_takable=1)) // CHECK-64-NEXT: (field name=optionalCFunction offset=56 // CHECK-64-NEXT: (single_payload_enum size=8 alignment=8 stride=8 num_extra_inhabitants=[[PTR_XI_2_SUB_1]] bitwise_takable=1 // CHECK-64-NEXT: (case name=some index=0 offset=0 // CHECK-64-NEXT: (builtin size=8 alignment=8 stride=8 num_extra_inhabitants=[[PTR_XI_2]] bitwise_takable=1)) // CHECK-64-NEXT: (case name=none index=1)))) // CHECK-32: (struct TypeLowering.FunctionStruct) // CHECK-32-NEXT: (struct size=32 alignment=4 stride=32 num_extra_inhabitants=4096 bitwise_takable=1 // CHECK-32-NEXT: (field name=thickFunction offset=0 // CHECK-32-NEXT: (thick_function size=8 alignment=4 stride=8 num_extra_inhabitants=4096 bitwise_takable=1 // CHECK-32-NEXT: (field name=function offset=0 // CHECK-32-NEXT: (builtin size=4 alignment=4 stride=4 num_extra_inhabitants=4096 bitwise_takable=1)) // CHECK-32-NEXT: (field name=context offset=4 // CHECK-32-NEXT: (reference kind=strong refcounting=native)))) // CHECK-32-NEXT: (field name=optionalThickFunction offset=8 // CHECK-32-NEXT: (single_payload_enum size=8 alignment=4 stride=8 num_extra_inhabitants=4095 bitwise_takable=1 // CHECK-32-NEXT: (case name=some index=0 offset=0 // CHECK-32-NEXT: (thick_function size=8 alignment=4 stride=8 num_extra_inhabitants=4096 bitwise_takable=1 // CHECK-32-NEXT: (field name=function offset=0 // CHECK-32-NEXT: (builtin size=4 alignment=4 stride=4 num_extra_inhabitants=4096 bitwise_takable=1)) // CHECK-32-NEXT: (field name=context offset=4 // CHECK-32-NEXT: (reference kind=strong refcounting=native)))) // CHECK-32-NEXT: (case name=none index=1))) // CHECK-32-NEXT: (field name=thinFunction offset=16 // CHECK-32-NEXT: (builtin size=4 alignment=4 stride=4 num_extra_inhabitants=4096 bitwise_takable=1)) // CHECK-32-NEXT: (field name=optionalThinFunction offset=20 // CHECK-32-NEXT: (single_payload_enum size=4 alignment=4 stride=4 num_extra_inhabitants=4095 bitwise_takable=1 // CHECK-32-NEXT: (case name=some index=0 offset=0 // CHECK-32-NEXT: (builtin size=4 alignment=4 stride=4 num_extra_inhabitants=4096 bitwise_takable=1)) // CHECK-32-NEXT: (case name=none index=1))) // CHECK-32-NEXT: (field name=cFunction offset=24 // CHECK-32-NEXT: (builtin size=4 alignment=4 stride=4 num_extra_inhabitants=4096 bitwise_takable=1)) // CHECK-32-NEXT: (field name=optionalCFunction offset=28 // CHECK-32-NEXT: (single_payload_enum size=4 alignment=4 stride=4 num_extra_inhabitants=4095 bitwise_takable=1 // CHECK-32-NEXT: (case name=some index=0 offset=0 // CHECK-32-NEXT: (builtin size=4 alignment=4 stride=4 num_extra_inhabitants=4096 bitwise_takable=1)) // CHECK-32-NEXT: (case name=none index=1)))) 12TypeLowering17ExistentialStructV // CHECK-64: (struct TypeLowering.ExistentialStruct) // CHECK-64-NEXT: (struct size=416 alignment=8 stride=416 num_extra_inhabitants=[[PTR_XI]] bitwise_takable=1 // CHECK-64-NEXT: (field name=any offset=0 // CHECK-64-NEXT: (opaque_existential size=32 alignment=8 stride=32 num_extra_inhabitants=[[PTR_XI]] bitwise_takable=1 // CHECK-64-NEXT: (field name=metadata offset=24 // CHECK-64-NEXT: (builtin size=8 alignment=8 stride=8 num_extra_inhabitants=[[PTR_XI]] bitwise_takable=1)))) // CHECK-64-NEXT: (field name=optionalAny offset=32 // CHECK-64-NEXT: (single_payload_enum size=32 alignment=8 stride=32 num_extra_inhabitants=[[PTR_XI_SUB_1]] bitwise_takable=1 // CHECK-64-NEXT: (case name=some index=0 offset=0 // CHECK-64-NEXT: (opaque_existential size=32 alignment=8 stride=32 num_extra_inhabitants=[[PTR_XI]] bitwise_takable=1 // CHECK-64-NEXT: (field name=metadata offset=24 // CHECK-64-NEXT: (builtin size=8 alignment=8 stride=8 num_extra_inhabitants=[[PTR_XI]] bitwise_takable=1)))) // CHECK-64-NEXT: (case name=none index=1))) // CHECK-64-NEXT: (field name=anyObject offset=64 // CHECK-64-NEXT: (class_existential size=8 alignment=8 stride=8 // CHECK-64-NEXT: (field name=object offset=0 // CHECK-64-NEXT: (reference kind=strong refcounting=unknown)))) // CHECK-64-NEXT: (field name=optionalAnyObject offset=72 // CHECK-64-NEXT: (single_payload_enum size=8 alignment=8 stride=8 num_extra_inhabitants=[[PTR_XI_SUB_1]] bitwise_takable=1 // CHECK-64-NEXT: (case name=some index=0 offset=0 // CHECK-64-NEXT: (class_existential size=8 alignment=8 stride=8 num_extra_inhabitants=[[PTR_XI]] bitwise_takable=1 // CHECK-64-NEXT: (field name=object offset=0 // CHECK-64-NEXT: (reference kind=strong refcounting=unknown)))) // CHECK-64-NEXT: (case name=none index=1))) // CHECK-64-NEXT: (field name=anyProto offset=80 // CHECK-64-NEXT: (opaque_existential size=40 alignment=8 stride=40 num_extra_inhabitants=[[PTR_XI]] bitwise_takable=1 // CHECK-64-NEXT: (field name=metadata offset=24 // CHECK-64-NEXT: (builtin size=8 alignment=8 stride=8 num_extra_inhabitants=[[PTR_XI]] bitwise_takable=1)) // CHECK-64-NEXT: (field name=wtable offset=32 // CHECK-64-NEXT: (builtin size=8 alignment=8 stride=8 num_extra_inhabitants=1 bitwise_takable=1)))) // CHECK-64-NEXT: (field name=optionalAnyProto offset=120 // CHECK-64-NEXT: (single_payload_enum size=40 alignment=8 stride=40 num_extra_inhabitants=[[PTR_XI_SUB_1]] bitwise_takable=1 // CHECK-64-NEXT: (case name=some index=0 offset=0 // CHECK-64-NEXT: (opaque_existential size=40 alignment=8 stride=40 num_extra_inhabitants=[[PTR_XI]] bitwise_takable=1 // CHECK-64-NEXT: (field name=metadata offset=24 // CHECK-64-NEXT: (builtin size=8 alignment=8 stride=8 num_extra_inhabitants=[[PTR_XI]] bitwise_takable=1)) // CHECK-64-NEXT: (field name=wtable offset=32 // CHECK-64-NEXT: (builtin size=8 alignment=8 stride=8 num_extra_inhabitants=1 bitwise_takable=1)))) // CHECK-64-NEXT: (case name=none index=1))) // CHECK-64-NEXT: (field name=anyProtoComposition offset=160 // CHECK-64-NEXT: (opaque_existential size=48 alignment=8 stride=48 num_extra_inhabitants=[[PTR_XI]] bitwise_takable=1 // CHECK-64-NEXT: (field name=metadata offset=24 // CHECK-64-NEXT: (builtin size=8 alignment=8 stride=8 num_extra_inhabitants=[[PTR_XI]] bitwise_takable=1)) // CHECK-64-NEXT: (field name=wtable offset=32 // CHECK-64-NEXT: (builtin size=8 alignment=8 stride=8 num_extra_inhabitants=1 bitwise_takable=1)) // CHECK-64-NEXT: (field name=wtable offset=40 // CHECK-64-NEXT: (builtin size=8 alignment=8 stride=8 num_extra_inhabitants=1 bitwise_takable=1)))) // CHECK-64-NEXT: (field name=optionalAnyProtoComposition offset=208 // CHECK-64-NEXT: (single_payload_enum size=48 alignment=8 stride=48 num_extra_inhabitants=[[PTR_XI_SUB_1]] bitwise_takable=1 // CHECK-64-NEXT: (case name=some index=0 offset=0 // CHECK-64-NEXT: (opaque_existential size=48 alignment=8 stride=48 num_extra_inhabitants=[[PTR_XI]] bitwise_takable=1 // CHECK-64-NEXT: (field name=metadata offset=24 // CHECK-64-NEXT: (builtin size=8 alignment=8 stride=8 num_extra_inhabitants=[[PTR_XI]] bitwise_takable=1)) // CHECK-64-NEXT: (field name=wtable offset=32 // CHECK-64-NEXT: (builtin size=8 alignment=8 stride=8 num_extra_inhabitants=1 bitwise_takable=1)) // CHECK-64-NEXT: (field name=wtable offset=40 // CHECK-64-NEXT: (builtin size=8 alignment=8 stride=8 num_extra_inhabitants=1 bitwise_takable=1)))) // CHECK-64-NEXT: (case name=none index=1))) // CHECK-64-NEXT: (field name=anyClassBoundProto1 offset=256 // CHECK-64-NEXT: (class_existential size=16 alignment=8 stride=16 num_extra_inhabitants=[[PTR_XI]] bitwise_takable=1 // CHECK-64-NEXT: (field name=object offset=0 // CHECK-64-NEXT: (reference kind=strong refcounting=unknown)) // CHECK-64-NEXT: (field name=wtable offset=8 // CHECK-64-NEXT: (builtin size=8 alignment=8 stride=8 num_extra_inhabitants=1 bitwise_takable=1)))) // CHECK-64-NEXT: (field name=optionalAnyClassBoundProto1 offset=272 // CHECK-64-NEXT: (single_payload_enum size=16 alignment=8 stride=16 num_extra_inhabitants=[[PTR_XI_SUB_1]] bitwise_takable=1 // CHECK-64-NEXT: (case name=some index=0 offset=0 // CHECK-64-NEXT: (class_existential size=16 alignment=8 stride=16 num_extra_inhabitants=[[PTR_XI]] bitwise_takable=1 // CHECK-64-NEXT: (field name=object offset=0 // CHECK-64-NEXT: (reference kind=strong refcounting=unknown)) // CHECK-64-NEXT: (field name=wtable offset=8 // CHECK-64-NEXT: (builtin size=8 alignment=8 stride=8 num_extra_inhabitants=1 bitwise_takable=1)))) // CHECK-64-NEXT: (case name=none index=1))) // CHECK-64-NEXT: (field name=anyClassBoundProto2 offset=288 // CHECK-64-NEXT: (class_existential size=16 alignment=8 stride=16 num_extra_inhabitants=[[PTR_XI]] bitwise_takable=1 // CHECK-64-NEXT: (field name=object offset=0 // CHECK-64-NEXT: (reference kind=strong refcounting=unknown)) // CHECK-64-NEXT: (field name=wtable offset=8 // CHECK-64-NEXT: (builtin size=8 alignment=8 stride=8 num_extra_inhabitants=1 bitwise_takable=1)))) // CHECK-64-NEXT: (field name=optionalAnyClassBoundProto2 offset=304 // CHECK-64-NEXT: (single_payload_enum size=16 alignment=8 stride=16 num_extra_inhabitants=[[PTR_XI_SUB_1]] bitwise_takable=1 // CHECK-64-NEXT: (case name=some index=0 offset=0 // CHECK-64-NEXT: (class_existential size=16 alignment=8 stride=16 num_extra_inhabitants=[[PTR_XI]] bitwise_takable=1 // CHECK-64-NEXT: (field name=object offset=0 // CHECK-64-NEXT: (reference kind=strong refcounting=unknown)) // CHECK-64-NEXT: (field name=wtable offset=8 // CHECK-64-NEXT: (builtin size=8 alignment=8 stride=8 num_extra_inhabitants=1 bitwise_takable=1)))) // CHECK-64-NEXT: (case name=none index=1))) // CHECK-64-NEXT: (field name=anyClassBoundProtoComposition1 offset=320 // CHECK-64-NEXT: (class_existential size=16 alignment=8 stride=16 num_extra_inhabitants=[[PTR_XI]] bitwise_takable=1 // CHECK-64-NEXT: (field name=object offset=0 // CHECK-64-NEXT: (reference kind=strong refcounting=unknown)) // CHECK-64-NEXT: (field name=wtable offset=8 // CHECK-64-NEXT: (builtin size=8 alignment=8 stride=8 num_extra_inhabitants=1 bitwise_takable=1)))) // CHECK-64-NEXT: (field name=optionalAnyClassBoundProtoComposition1 offset=336 // CHECK-64-NEXT: (single_payload_enum size=16 alignment=8 stride=16 num_extra_inhabitants=[[PTR_XI_SUB_1]] bitwise_takable=1 // CHECK-64-NEXT: (case name=some index=0 offset=0 // CHECK-64-NEXT: (class_existential size=16 alignment=8 stride=16 num_extra_inhabitants=[[PTR_XI]] bitwise_takable=1 // CHECK-64-NEXT: (field name=object offset=0 // CHECK-64-NEXT: (reference kind=strong refcounting=unknown)) // CHECK-64-NEXT: (field name=wtable offset=8 // CHECK-64-NEXT: (builtin size=8 alignment=8 stride=8 num_extra_inhabitants=1 bitwise_takable=1)))) // CHECK-64-NEXT: (case name=none index=1))) // CHECK-64-NEXT: (field name=anyClassBoundProtoComposition2 offset=352 // CHECK-64-NEXT: (class_existential size=24 alignment=8 stride=24 num_extra_inhabitants=[[PTR_XI]] bitwise_takable=1 // CHECK-64-NEXT: (field name=object offset=0 // CHECK-64-NEXT: (reference kind=strong refcounting=unknown)) // CHECK-64-NEXT: (field name=wtable offset=8 // CHECK-64-NEXT: (builtin size=8 alignment=8 stride=8 num_extra_inhabitants=1 bitwise_takable=1)) // CHECK-64-NEXT: (field name=wtable offset=16 // CHECK-64-NEXT: (builtin size=8 alignment=8 stride=8 num_extra_inhabitants=1 bitwise_takable=1)))) // CHECK-64-NEXT: (field name=optionalAnyClassBoundProtoComposition2 offset=376 // CHECK-64-NEXT: (single_payload_enum size=24 alignment=8 stride=24 num_extra_inhabitants=[[PTR_XI_SUB_1]] bitwise_takable=1 // CHECK-64-NEXT: (case name=some index=0 offset=0 // CHECK-64-NEXT: (class_existential size=24 alignment=8 stride=24 num_extra_inhabitants=[[PTR_XI]] bitwise_takable=1 // CHECK-64-NEXT: (field name=object offset=0 // CHECK-64-NEXT: (reference kind=strong refcounting=unknown)) // CHECK-64-NEXT: (field name=wtable offset=8 // CHECK-64-NEXT: (builtin size=8 alignment=8 stride=8 num_extra_inhabitants=1 bitwise_takable=1)) // CHECK-64-NEXT: (field name=wtable offset=16 // CHECK-64-NEXT: (builtin size=8 alignment=8 stride=8 num_extra_inhabitants=1 bitwise_takable=1)))) // CHECK-64-NEXT: (case name=none index=1))) // CHECK-64-NEXT: (field name=classConstrainedP1 offset=400 // CHECK-64-NEXT: (class_existential size=16 alignment=8 stride=16 num_extra_inhabitants=[[PTR_XI]] bitwise_takable=1 // CHECK-64-NEXT: (field name=object offset=0 // CHECK-64-NEXT: (reference kind=strong refcounting=native)) // CHECK-64-NEXT: (field name=wtable offset=8 // CHECK-64-NEXT: (builtin size=8 alignment=8 stride=8 num_extra_inhabitants=1 bitwise_takable=1))))) // CHECK-32: (struct TypeLowering.ExistentialStruct) // CHECK-32-NEXT: (struct size=208 alignment=4 stride=208 num_extra_inhabitants=4096 bitwise_takable=1 // CHECK-32-NEXT: (field name=any offset=0 // CHECK-32-NEXT: (opaque_existential size=16 alignment=4 stride=16 num_extra_inhabitants=4096 bitwise_takable=1 // CHECK-32-NEXT: (field name=metadata offset=12 // CHECK-32-NEXT: (builtin size=4 alignment=4 stride=4 num_extra_inhabitants=4096 bitwise_takable=1)))) // CHECK-32-NEXT: (field name=optionalAny offset=16 // CHECK-32-NEXT: (single_payload_enum size=16 alignment=4 stride=16 num_extra_inhabitants=4095 bitwise_takable=1 // CHECK-32-NEXT: (case name=some index=0 offset=0 // CHECK-32-NEXT: (opaque_existential size=16 alignment=4 stride=16 num_extra_inhabitants=4096 bitwise_takable=1 // CHECK-32-NEXT: (field name=metadata offset=12 // CHECK-32-NEXT: (builtin size=4 alignment=4 stride=4 num_extra_inhabitants=4096 bitwise_takable=1)))) // CHECK-32-NEXT: (case name=none index=1))) // CHECK-32-NEXT: (field name=anyObject offset=32 // CHECK-32-NEXT: (class_existential size=4 alignment=4 stride=4 num_extra_inhabitants=4096 bitwise_takable=1 // CHECK-32-NEXT: (field name=object offset=0 // CHECK-32-NEXT: (reference kind=strong refcounting=unknown)))) // CHECK-32-NEXT: (field name=optionalAnyObject offset=36 // CHECK-32-NEXT: (single_payload_enum size=4 alignment=4 stride=4 num_extra_inhabitants=4095 bitwise_takable=1 // CHECK-32-NEXT: (case name=some index=0 offset=0 // CHECK-32-NEXT: (class_existential size=4 alignment=4 stride=4 num_extra_inhabitants=4096 bitwise_takable=1 // CHECK-32-NEXT: (field name=object offset=0 // CHECK-32-NEXT: (reference kind=strong refcounting=unknown)))) // CHECK-32-NEXT: (case name=none index=1))) // CHECK-32-NEXT: (field name=anyProto offset=40 // CHECK-32-NEXT: (opaque_existential size=20 alignment=4 stride=20 num_extra_inhabitants=4096 bitwise_takable=1 // CHECK-32-NEXT: (field name=metadata offset=12 // CHECK-32-NEXT: (builtin size=4 alignment=4 stride=4 num_extra_inhabitants=4096 bitwise_takable=1)) // CHECK-32-NEXT: (field name=wtable offset=16 // CHECK-32-NEXT: (builtin size=4 alignment=4 stride=4 num_extra_inhabitants=1 bitwise_takable=1)))) // CHECK-32-NEXT: (field name=optionalAnyProto offset=60 // CHECK-32-NEXT: (single_payload_enum size=20 alignment=4 stride=20 num_extra_inhabitants=4095 bitwise_takable=1 // CHECK-32-NEXT: (case name=some index=0 offset=0 // CHECK-32-NEXT: (opaque_existential size=20 alignment=4 stride=20 num_extra_inhabitants=4096 bitwise_takable=1 // CHECK-32-NEXT: (field name=metadata offset=12 // CHECK-32-NEXT: (builtin size=4 alignment=4 stride=4 num_extra_inhabitants=4096 bitwise_takable=1)) // CHECK-32-NEXT: (field name=wtable offset=16 // CHECK-32-NEXT: (builtin size=4 alignment=4 stride=4 num_extra_inhabitants=1 bitwise_takable=1)))) // CHECK-32-NEXT: (case name=none index=1))) // CHECK-32-NEXT: (field name=anyProtoComposition offset=80 // CHECK-32-NEXT: (opaque_existential size=24 alignment=4 stride=24 num_extra_inhabitants=4096 bitwise_takable=1 // CHECK-32-NEXT: (field name=metadata offset=12 // CHECK-32-NEXT: (builtin size=4 alignment=4 stride=4 num_extra_inhabitants=4096 bitwise_takable=1)) // CHECK-32-NEXT: (field name=wtable offset=16 // CHECK-32-NEXT: (builtin size=4 alignment=4 stride=4 num_extra_inhabitants=1 bitwise_takable=1)) // CHECK-32-NEXT: (field name=wtable offset=20 // CHECK-32-NEXT: (builtin size=4 alignment=4 stride=4 num_extra_inhabitants=1 bitwise_takable=1)))) // CHECK-32-NEXT: (field name=optionalAnyProtoComposition offset=104 // CHECK-32-NEXT: (single_payload_enum size=24 alignment=4 stride=24 num_extra_inhabitants=4095 bitwise_takable=1 // CHECK-32-NEXT: (case name=some index=0 offset=0 // CHECK-32-NEXT: (opaque_existential size=24 alignment=4 stride=24 num_extra_inhabitants=4096 bitwise_takable=1 // CHECK-32-NEXT: (field name=metadata offset=12 // CHECK-32-NEXT: (builtin size=4 alignment=4 stride=4 num_extra_inhabitants=4096 bitwise_takable=1)) // CHECK-32-NEXT: (field name=wtable offset=16 // CHECK-32-NEXT: (builtin size=4 alignment=4 stride=4 num_extra_inhabitants=1 bitwise_takable=1)) // CHECK-32-NEXT: (field name=wtable offset=20 // CHECK-32-NEXT: (builtin size=4 alignment=4 stride=4 num_extra_inhabitants=1 bitwise_takable=1)))) // CHECK-32-NEXT: (case name=none index=1))) // CHECK-32-NEXT: (field name=anyClassBoundProto1 offset=128 // CHECK-32-NEXT: (class_existential size=8 alignment=4 stride=8 num_extra_inhabitants=4096 bitwise_takable=1 // CHECK-32-NEXT: (field name=object offset=0 // CHECK-32-NEXT: (reference kind=strong refcounting=unknown)) // CHECK-32-NEXT: (field name=wtable offset=4 // CHECK-32-NEXT: (builtin size=4 alignment=4 stride=4 num_extra_inhabitants=1 bitwise_takable=1)))) // CHECK-32-NEXT: (field name=optionalAnyClassBoundProto1 offset=136 // CHECK-32-NEXT: (single_payload_enum size=8 alignment=4 stride=8 num_extra_inhabitants=4095 bitwise_takable=1 // CHECK-32-NEXT: (case name=some index=0 offset=0 // CHECK-32-NEXT: (class_existential size=8 alignment=4 stride=8 num_extra_inhabitants=4096 bitwise_takable=1 // CHECK-32-NEXT: (field name=object offset=0 // CHECK-32-NEXT: (reference kind=strong refcounting=unknown)) // CHECK-32-NEXT: (field name=wtable offset=4 // CHECK-32-NEXT: (builtin size=4 alignment=4 stride=4 num_extra_inhabitants=1 bitwise_takable=1)))) // CHECK-32-NEXT: (case name=none index=1))) // CHECK-32-NEXT: (field name=anyClassBoundProto2 offset=144 // CHECK-32-NEXT: (class_existential size=8 alignment=4 stride=8 num_extra_inhabitants=4096 bitwise_takable=1 // CHECK-32-NEXT: (field name=object offset=0 // CHECK-32-NEXT: (reference kind=strong refcounting=unknown)) // CHECK-32-NEXT: (field name=wtable offset=4 // CHECK-32-NEXT: (builtin size=4 alignment=4 stride=4 num_extra_inhabitants=1 bitwise_takable=1)))) // CHECK-32-NEXT: (field name=optionalAnyClassBoundProto2 offset=152 // CHECK-32-NEXT: (single_payload_enum size=8 alignment=4 stride=8 num_extra_inhabitants=4095 bitwise_takable=1 // CHECK-32-NEXT: (case name=some index=0 offset=0 // CHECK-32-NEXT: (class_existential size=8 alignment=4 stride=8 num_extra_inhabitants=4096 bitwise_takable=1 // CHECK-32-NEXT: (field name=object offset=0 // CHECK-32-NEXT: (reference kind=strong refcounting=unknown)) // CHECK-32-NEXT: (field name=wtable offset=4 // CHECK-32-NEXT: (builtin size=4 alignment=4 stride=4 num_extra_inhabitants=1 bitwise_takable=1)))) // CHECK-32-NEXT: (case name=none index=1))) // CHECK-32-NEXT: (field name=anyClassBoundProtoComposition1 offset=160 // CHECK-32-NEXT: (class_existential size=8 alignment=4 stride=8 num_extra_inhabitants=4096 bitwise_takable=1 // CHECK-32-NEXT: (field name=object offset=0 // CHECK-32-NEXT: (reference kind=strong refcounting=unknown)) // CHECK-32-NEXT: (field name=wtable offset=4 // CHECK-32-NEXT: (builtin size=4 alignment=4 stride=4 num_extra_inhabitants=1 bitwise_takable=1)))) // CHECK-32-NEXT: (field name=optionalAnyClassBoundProtoComposition1 offset=168 // CHECK-32-NEXT: (single_payload_enum size=8 alignment=4 stride=8 num_extra_inhabitants=4095 bitwise_takable=1 // CHECK-32-NEXT: (case name=some index=0 offset=0 // CHECK-32-NEXT: (class_existential size=8 alignment=4 stride=8 num_extra_inhabitants=4096 bitwise_takable=1 // CHECK-32-NEXT: (field name=object offset=0 // CHECK-32-NEXT: (reference kind=strong refcounting=unknown)) // CHECK-32-NEXT: (field name=wtable offset=4 // CHECK-32-NEXT: (builtin size=4 alignment=4 stride=4 num_extra_inhabitants=1 bitwise_takable=1)))) // CHECK-32-NEXT: (case name=none index=1))) // CHECK-32-NEXT: (field name=anyClassBoundProtoComposition2 offset=176 // CHECK-32-NEXT: (class_existential size=12 alignment=4 stride=12 num_extra_inhabitants=4096 bitwise_takable=1 // CHECK-32-NEXT: (field name=object offset=0 // CHECK-32-NEXT: (reference kind=strong refcounting=unknown)) // CHECK-32-NEXT: (field name=wtable offset=4 // CHECK-32-NEXT: (builtin size=4 alignment=4 stride=4 num_extra_inhabitants=1 bitwise_takable=1)) // CHECK-32-NEXT: (field name=wtable offset=8 // CHECK-32-NEXT: (builtin size=4 alignment=4 stride=4 num_extra_inhabitants=1 bitwise_takable=1)))) // CHECK-32-NEXT: (field name=optionalAnyClassBoundProtoComposition2 offset=188 // CHECK-32-NEXT: (single_payload_enum size=12 alignment=4 stride=12 num_extra_inhabitants=4095 bitwise_takable=1 // CHECK-32-NEXT: (case name=some index=0 offset=0 // CHECK-32-NEXT: (class_existential size=12 alignment=4 stride=12 num_extra_inhabitants=4096 bitwise_takable=1 // CHECK-32-NEXT: (field name=object offset=0 // CHECK-32-NEXT: (reference kind=strong refcounting=unknown)) // CHECK-32-NEXT: (field name=wtable offset=4 // CHECK-32-NEXT: (builtin size=4 alignment=4 stride=4 num_extra_inhabitants=1 bitwise_takable=1)) // CHECK-32-NEXT: (field name=wtable offset=8 // CHECK-32-NEXT: (builtin size=4 alignment=4 stride=4 num_extra_inhabitants=1 bitwise_takable=1)))) // CHECK-32-NEXT: (case name=none index=1))) // CHECK-32-NEXT: (field name=classConstrainedP1 offset=200 // CHECK-32-NEXT: (class_existential size=8 alignment=4 stride=8 num_extra_inhabitants=4096 bitwise_takable=1 // CHECK-32-NEXT: (field name=object offset=0 // CHECK-32-NEXT: (reference kind=strong refcounting=native)) // CHECK-32-NEXT: (field name=wtable offset=4 // CHECK-32-NEXT: (builtin size=4 alignment=4 stride=4 num_extra_inhabitants=1 bitwise_takable=1))))) 12TypeLowering24UnownedExistentialStructV // CHECK-64: (struct size=16 alignment=8 stride=16 num_extra_inhabitants=[[PTR_XI]] bitwise_takable=0 // CHECK-64-NEXT: (field name=unownedRef offset=0 // CHECK-64-NEXT: (class_existential size=16 alignment=8 stride=16 num_extra_inhabitants=[[PTR_XI]] bitwise_takable=0 // CHECK-64-NEXT: (field name=object offset=0 // CHECK-64-NEXT: (reference kind=unowned refcounting=unknown)) // CHECK-64-NEXT: (field name=wtable offset=8 // CHECK-64-NEXT: (builtin size=8 alignment=8 stride=8 num_extra_inhabitants=1 bitwise_takable=1))))) // CHECK-32: (struct size=8 alignment=4 stride=8 num_extra_inhabitants=4096 bitwise_takable=0 // CHECK-32-NEXT: (field name=unownedRef offset=0 // CHECK-32-NEXT: (class_existential size=8 alignment=4 stride=8 num_extra_inhabitants=4096 bitwise_takable=0 // CHECK-32-NEXT: (field name=object offset=0 // CHECK-32-NEXT: (reference kind=unowned refcounting=unknown)) // CHECK-32-NEXT: (field name=wtable offset=4 // CHECK-32-NEXT: (builtin size=4 alignment=4 stride=4 num_extra_inhabitants=1 bitwise_takable=1))))) 12TypeLowering30UnownedNativeExistentialStructV // CHECK-64: (struct TypeLowering.UnownedNativeExistentialStruct) // CHECK-64-NEXT: (struct size=48 alignment=8 stride=48 num_extra_inhabitants=[[PTR_XI]] bitwise_takable=1 // CHECK-64-NEXT: (field name=unownedRef1 offset=0 // CHECK-64-NEXT: (class_existential size=16 alignment=8 stride=16 num_extra_inhabitants=[[PTR_XI]] bitwise_takable=1 // CHECK-64-NEXT: (field name=object offset=0 // CHECK-64-NEXT: (reference kind=unowned refcounting=native)) // CHECK-64-NEXT: (field name=wtable offset=8 // CHECK-64-NEXT: (builtin size=8 alignment=8 stride=8 num_extra_inhabitants=1 bitwise_takable=1)))) // CHECK-64-NEXT: (field name=unownedRef2 offset=16 // CHECK-64-NEXT: (class_existential size=16 alignment=8 stride=16 num_extra_inhabitants=[[PTR_XI]] bitwise_takable=1 // CHECK-64-NEXT: (field name=object offset=0 // CHECK-64-NEXT: (reference kind=unowned refcounting=native)) // CHECK-64-NEXT: (field name=wtable offset=8 // CHECK-64-NEXT: (builtin size=8 alignment=8 stride=8 num_extra_inhabitants=1 bitwise_takable=1)))) // CHECK-64-NEXT: (field name=unownedRef3 offset=32 // CHECK-64-NEXT: (class_existential size=16 alignment=8 stride=16 num_extra_inhabitants=[[PTR_XI]] bitwise_takable=1 // CHECK-64-NEXT: (field name=object offset=0 // CHECK-64-NEXT: (reference kind=unowned refcounting=native)) // CHECK-64-NEXT: (field name=wtable offset=8 // CHECK-64-NEXT: (builtin size=8 alignment=8 stride=8 num_extra_inhabitants=1 bitwise_takable=1))))) // CHECK-32: (struct TypeLowering.UnownedNativeExistentialStruct) // CHECK-32-NEXT: (struct size=24 alignment=4 stride=24 num_extra_inhabitants=4096 bitwise_takable=1 // CHECK-32-NEXT: (field name=unownedRef1 offset=0 // CHECK-32-NEXT: (class_existential size=8 alignment=4 stride=8 num_extra_inhabitants=4096 bitwise_takable=1 // CHECK-32-NEXT: (field name=object offset=0 // CHECK-32-NEXT: (reference kind=unowned refcounting=native)) // CHECK-32-NEXT: (field name=wtable offset=4 // CHECK-32-NEXT: (builtin size=4 alignment=4 stride=4 num_extra_inhabitants=1 bitwise_takable=1)))) // CHECK-32-NEXT: (field name=unownedRef2 offset=8 // CHECK-32-NEXT: (class_existential size=8 alignment=4 stride=8 num_extra_inhabitants=4096 bitwise_takable=1 // CHECK-32-NEXT: (field name=object offset=0 // CHECK-32-NEXT: (reference kind=unowned refcounting=native)) // CHECK-32-NEXT: (field name=wtable offset=4 // CHECK-32-NEXT: (builtin size=4 alignment=4 stride=4 num_extra_inhabitants=1 bitwise_takable=1)))) // CHECK-32-NEXT: (field name=unownedRef3 offset=16 // CHECK-32-NEXT: (class_existential size=8 alignment=4 stride=8 num_extra_inhabitants=4096 bitwise_takable=1 // CHECK-32-NEXT: (field name=object offset=0 // CHECK-32-NEXT: (reference kind=unowned refcounting=native)) // CHECK-32-NEXT: (field name=wtable offset=4 // CHECK-32-NEXT: (builtin size=4 alignment=4 stride=4 num_extra_inhabitants=1 bitwise_takable=1))))) 12TypeLowering21WeakExistentialStructV // CHECK-64-NEXT: (struct TypeLowering.WeakExistentialStruct) // CHECK-64-NEXT: (struct size=24 alignment=8 stride=24 num_extra_inhabitants=[[PTR_XI]] bitwise_takable=0 // CHECK-64-NEXT: (field name=weakAnyObject offset=0 // CHECK-64-NEXT: (class_existential size=8 alignment=8 stride=8 num_extra_inhabitants=[[PTR_XI]] bitwise_takable=0 // CHECK-64-NEXT: (field name=object offset=0 // CHECK-64-NEXT: (reference kind=weak refcounting=unknown)))) // CHECK-64-NEXT: (field name=weakAnyClassBoundProto offset=8 // CHECK-64-NEXT: (class_existential size=16 alignment=8 stride=16 num_extra_inhabitants=[[PTR_XI]] bitwise_takable=0 // CHECK-64-NEXT: (field name=object offset=0 // CHECK-64-NEXT: (reference kind=weak refcounting=unknown)) // CHECK-64-NEXT: (field name=wtable offset=8 // CHECK-64-NEXT: (builtin size=8 alignment=8 stride=8 num_extra_inhabitants=1 bitwise_takable=1))))) // CHECK-32-NEXT: (struct TypeLowering.WeakExistentialStruct) // CHECK-32-NEXT: (struct size=12 alignment=4 stride=12 num_extra_inhabitants=4096 bitwise_takable=0 // CHECK-32-NEXT: (field name=weakAnyObject offset=0 // CHECK-32-NEXT: (class_existential size=4 alignment=4 stride=4 num_extra_inhabitants=4096 bitwise_takable=0 // CHECK-32-NEXT: (field name=object offset=0 // CHECK-32-NEXT: (reference kind=weak refcounting=unknown)))) // CHECK-32-NEXT: (field name=weakAnyClassBoundProto offset=4 // CHECK-32-NEXT: (class_existential size=8 alignment=4 stride=8 num_extra_inhabitants=4096 bitwise_takable=0 // CHECK-32-NEXT: (field name=object offset=0 // CHECK-32-NEXT: (reference kind=weak refcounting=unknown)) // CHECK-32-NEXT: (field name=wtable offset=4 // CHECK-32-NEXT: (builtin size=4 alignment=4 stride=4 num_extra_inhabitants=1 bitwise_takable=1))))) 12TypeLowering26UnmanagedExistentialStructV // CHECK-64: (struct TypeLowering.UnmanagedExistentialStruct) // CHECK-64-NEXT: (struct size=16 alignment=8 stride=16 num_extra_inhabitants=[[PTR_XI]] bitwise_takable=1 // CHECK-64-NEXT: (field name=unmanagedRef offset=0 // CHECK-64-NEXT: (class_existential size=16 alignment=8 stride=16 num_extra_inhabitants=[[PTR_XI]] bitwise_takable=1 // CHECK-64-NEXT: (field name=object offset=0 // CHECK-64-NEXT: (reference kind=unmanaged refcounting=unknown)) // CHECK-64-NEXT: (field name=wtable offset=8 // CHECK-64-NEXT: (builtin size=8 alignment=8 stride=8 num_extra_inhabitants=1 bitwise_takable=1))))) // CHECK-32: (struct TypeLowering.UnmanagedExistentialStruct) // CHECK-32-NEXT: (struct size=8 alignment=4 stride=8 num_extra_inhabitants=4096 bitwise_takable=1 // CHECK-32-NEXT: (field name=unmanagedRef offset=0 // CHECK-32-NEXT: (class_existential size=8 alignment=4 stride=8 num_extra_inhabitants=4096 bitwise_takable=1 // CHECK-32-NEXT: (field name=object offset=0 // CHECK-32-NEXT: (reference kind=unmanaged refcounting=unknown)) // CHECK-32-NEXT: (field name=wtable offset=4 // CHECK-32-NEXT: (builtin size=4 alignment=4 stride=4 num_extra_inhabitants=1 bitwise_takable=1))))) 12TypeLowering14MetatypeStructV // CHECK-64: (struct TypeLowering.MetatypeStruct) // CHECK-64-NEXT: (struct size=152 alignment=8 stride=152 num_extra_inhabitants=[[PTR_XI]] bitwise_takable=1 // CHECK-64-NEXT: (field name=any offset=0 // CHECK-64-NEXT: (existential_metatype size=8 alignment=8 stride=8 num_extra_inhabitants=[[PTR_XI]] bitwise_takable=1 // CHECK-64-NEXT: (field name=metadata offset=0 // CHECK-64-NEXT: (builtin size=8 alignment=8 stride=8 num_extra_inhabitants=[[PTR_XI]] bitwise_takable=1)))) // CHECK-64-NEXT: (field name=optionalAny offset=8 // CHECK-64-NEXT: (single_payload_enum size=8 alignment=8 stride=8 num_extra_inhabitants=[[PTR_XI_SUB_1]] bitwise_takable=1 // CHECK-64-NEXT: (case name=some index=0 offset=0 // CHECK-64-NEXT: (existential_metatype size=8 alignment=8 stride=8 num_extra_inhabitants=[[PTR_XI]] bitwise_takable=1 // CHECK-64-NEXT: (field name=metadata offset=0 // CHECK-64-NEXT: (builtin size=8 alignment=8 stride=8 num_extra_inhabitants=[[PTR_XI]] bitwise_takable=1)))) // CHECK-64-NEXT: (case name=none index=1))) // CHECK-64-NEXT: (field name=anyObject offset=16 // CHECK-64-NEXT: (existential_metatype size=8 alignment=8 stride=8 num_extra_inhabitants=[[PTR_XI]] bitwise_takable=1 // CHECK-64-NEXT: (field name=metadata offset=0 // CHECK-64-NEXT: (builtin size=8 alignment=8 stride=8 num_extra_inhabitants=[[PTR_XI]] bitwise_takable=1)))) // CHECK-64-NEXT: (field name=optionalAnyObject offset=24 // CHECK-64-NEXT: (single_payload_enum size=8 alignment=8 stride=8 num_extra_inhabitants=[[PTR_XI_SUB_1]] bitwise_takable=1 // CHECK-64-NEXT: (case name=some index=0 offset=0 // CHECK-64-NEXT: (existential_metatype size=8 alignment=8 stride=8 num_extra_inhabitants=[[PTR_XI]] bitwise_takable=1 // CHECK-64-NEXT: (field name=metadata offset=0 // CHECK-64-NEXT: (builtin size=8 alignment=8 stride=8 num_extra_inhabitants=[[PTR_XI]] bitwise_takable=1)))) // CHECK-64-NEXT: (case name=none index=1))) // CHECK-64-NEXT: (field name=anyProto offset=32 // CHECK-64-NEXT: (existential_metatype size=16 alignment=8 stride=16 num_extra_inhabitants=[[PTR_XI]] bitwise_takable=1 // CHECK-64-NEXT: (field name=metadata offset=0 // CHECK-64-NEXT: (builtin size=8 alignment=8 stride=8 num_extra_inhabitants=[[PTR_XI]] bitwise_takable=1)) // CHECK-64-NEXT: (field name=wtable offset=8 // CHECK-64-NEXT: (builtin size=8 alignment=8 stride=8 num_extra_inhabitants=1 bitwise_takable=1)))) // CHECK-64-NEXT: (field name=optionalAnyProto offset=48 // CHECK-64-NEXT: (single_payload_enum size=16 alignment=8 stride=16 num_extra_inhabitants=[[PTR_XI_SUB_1]] bitwise_takable=1 // CHECK-64-NEXT: (case name=some index=0 offset=0 // CHECK-64-NEXT: (existential_metatype size=16 alignment=8 stride=16 num_extra_inhabitants=[[PTR_XI]] bitwise_takable=1 // CHECK-64-NEXT: (field name=metadata offset=0 // CHECK-64-NEXT: (builtin size=8 alignment=8 stride=8 num_extra_inhabitants=[[PTR_XI]] bitwise_takable=1)) // CHECK-64-NEXT: (field name=wtable offset=8 // CHECK-64-NEXT: (builtin size=8 alignment=8 stride=8 num_extra_inhabitants=1 bitwise_takable=1)))) // CHECK-64-NEXT: (case name=none index=1))) // CHECK-64-NEXT: (field name=anyProtoComposition offset=64 // CHECK-64-NEXT: (existential_metatype size=24 alignment=8 stride=24 num_extra_inhabitants=[[PTR_XI]] bitwise_takable=1 // CHECK-64-NEXT: (field name=metadata offset=0 // CHECK-64-NEXT: (builtin size=8 alignment=8 stride=8 num_extra_inhabitants=[[PTR_XI]] bitwise_takable=1)) // CHECK-64-NEXT: (field name=wtable offset=8 // CHECK-64-NEXT: (builtin size=8 alignment=8 stride=8 num_extra_inhabitants=1 bitwise_takable=1)) // CHECK-64-NEXT: (field name=wtable offset=16 // CHECK-64-NEXT: (builtin size=8 alignment=8 stride=8 num_extra_inhabitants=1 bitwise_takable=1)))) // CHECK-64-NEXT: (field name=optionalAnyProtoComposition offset=88 // CHECK-64-NEXT: (single_payload_enum size=24 alignment=8 stride=24 num_extra_inhabitants=[[PTR_XI_SUB_1]] bitwise_takable=1 // CHECK-64-NEXT: (case name=some index=0 offset=0 // CHECK-64-NEXT: (existential_metatype size=24 alignment=8 stride=24 num_extra_inhabitants=[[PTR_XI]] bitwise_takable=1 // CHECK-64-NEXT: (field name=metadata offset=0 // CHECK-64-NEXT: (builtin size=8 alignment=8 stride=8 num_extra_inhabitants=[[PTR_XI]] bitwise_takable=1)) // CHECK-64-NEXT: (field name=wtable offset=8 // CHECK-64-NEXT: (builtin size=8 alignment=8 stride=8 num_extra_inhabitants=1 bitwise_takable=1)) // CHECK-64-NEXT: (field name=wtable offset=16 // CHECK-64-NEXT: (builtin size=8 alignment=8 stride=8 num_extra_inhabitants=1 bitwise_takable=1)))) // CHECK-64-NEXT: (case name=none index=1))) // CHECK-64-NEXT: (field name=structMetatype offset=112 // CHECK-64-NEXT: (builtin size=0 alignment=1 stride=1 num_extra_inhabitants=0 bitwise_takable=1)) // CHECK-64-NEXT: (field name=optionalStructMetatype offset=112 // CHECK-64-NEXT: (single_payload_enum size=8 alignment=8 stride=8 num_extra_inhabitants=[[PTR_XI_SUB_1]] bitwise_takable=1 // CHECK-64-NEXT: (case name=some index=0 offset=0 // CHECK-64-NEXT: (builtin size=8 alignment=8 stride=8 num_extra_inhabitants=[[PTR_XI]] bitwise_takable=1)) // CHECK-64-NEXT: (case name=none index=1))) // CHECK-64-NEXT: (field name=classMetatype offset=120 // CHECK-64-NEXT: (builtin size=8 alignment=8 stride=8 num_extra_inhabitants=[[PTR_XI]] bitwise_takable=1)) // CHECK-64-NEXT: (field name=optionalClassMetatype offset=128 // CHECK-64-NEXT: (single_payload_enum size=8 alignment=8 stride=8 num_extra_inhabitants=[[PTR_XI_SUB_1]] bitwise_takable=1 // CHECK-64-NEXT: (case name=some index=0 offset=0 // CHECK-64-NEXT: (builtin size=8 alignment=8 stride=8 num_extra_inhabitants=[[PTR_XI]] bitwise_takable=1)) // CHECK-64-NEXT: (case name=none index=1))) // CHECK-64-NEXT: (field name=abstractMetatype offset=136 // CHECK-64-NEXT: (struct size=16 alignment=8 stride=16 num_extra_inhabitants=[[PTR_XI]] bitwise_takable=1 // CHECK-64-NEXT: (field name=t offset=0 // CHECK-64-NEXT: (builtin size=8 alignment=8 stride=8 num_extra_inhabitants=[[PTR_XI]] bitwise_takable=1)) // CHECK-64-NEXT: (field name=u offset=8 // CHECK-64-NEXT: (builtin size=8 alignment=8 stride=8 num_extra_inhabitants=[[PTR_XI]] bitwise_takable=1))))) // CHECK-32: (struct TypeLowering.MetatypeStruct) // CHECK-32-NEXT: (struct size=76 alignment=4 stride=76 num_extra_inhabitants=4096 // CHECK-32-NEXT: (field name=any offset=0 // CHECK-32-NEXT: (existential_metatype size=4 alignment=4 stride=4 num_extra_inhabitants=4096 bitwise_takable=1 // CHECK-32-NEXT: (field name=metadata offset=0 // CHECK-32-NEXT: (builtin size=4 alignment=4 stride=4 num_extra_inhabitants=4096 bitwise_takable=1)))) // CHECK-32-NEXT: (field name=optionalAny offset=4 // CHECK-32-NEXT: (single_payload_enum size=4 alignment=4 stride=4 num_extra_inhabitants=4095 bitwise_takable=1 // CHECK-32-NEXT: (case name=some index=0 offset=0 // CHECK-32-NEXT: (existential_metatype size=4 alignment=4 stride=4 num_extra_inhabitants=4096 bitwise_takable=1 // CHECK-32-NEXT: (field name=metadata offset=0 // CHECK-32-NEXT: (builtin size=4 alignment=4 stride=4 num_extra_inhabitants=4096 bitwise_takable=1)))) // CHECK-32-NEXT: (case name=none index=1))) // CHECK-32-NEXT: (field name=anyObject offset=8 // CHECK-32-NEXT: (existential_metatype size=4 alignment=4 stride=4 num_extra_inhabitants=4096 bitwise_takable=1 // CHECK-32-NEXT: (field name=metadata offset=0 // CHECK-32-NEXT: (builtin size=4 alignment=4 stride=4 num_extra_inhabitants=4096 bitwise_takable=1)))) // CHECK-32-NEXT: (field name=optionalAnyObject offset=12 // CHECK-32-NEXT: (single_payload_enum size=4 alignment=4 stride=4 num_extra_inhabitants=4095 bitwise_takable=1 // CHECK-32-NEXT: (case name=some index=0 offset=0 // CHECK-32-NEXT: (existential_metatype size=4 alignment=4 stride=4 num_extra_inhabitants=4096 bitwise_takable=1 // CHECK-32-NEXT: (field name=metadata offset=0 // CHECK-32-NEXT: (builtin size=4 alignment=4 stride=4 num_extra_inhabitants=4096 bitwise_takable=1)))) // CHECK-32-NEXT: (case name=none index=1))) // CHECK-32-NEXT: (field name=anyProto offset=16 // CHECK-32-NEXT: (existential_metatype size=8 alignment=4 stride=8 num_extra_inhabitants=4096 bitwise_takable=1 // CHECK-32-NEXT: (field name=metadata offset=0 // CHECK-32-NEXT: (builtin size=4 alignment=4 stride=4 num_extra_inhabitants=4096 bitwise_takable=1)) // CHECK-32-NEXT: (field name=wtable offset=4 // CHECK-32-NEXT: (builtin size=4 alignment=4 stride=4 num_extra_inhabitants=1 bitwise_takable=1)))) // CHECK-32-NEXT: (field name=optionalAnyProto offset=24 // CHECK-32-NEXT: (single_payload_enum size=8 alignment=4 stride=8 num_extra_inhabitants=4095 bitwise_takable=1 // CHECK-32-NEXT: (case name=some index=0 offset=0 // CHECK-32-NEXT: (existential_metatype size=8 alignment=4 stride=8 num_extra_inhabitants=4096 bitwise_takable=1 // CHECK-32-NEXT: (field name=metadata offset=0 // CHECK-32-NEXT: (builtin size=4 alignment=4 stride=4 num_extra_inhabitants=4096 bitwise_takable=1)) // CHECK-32-NEXT: (field name=wtable offset=4 // CHECK-32-NEXT: (builtin size=4 alignment=4 stride=4 num_extra_inhabitants=1 bitwise_takable=1)))) // CHECK-32-NEXT: (case name=none index=1))) // CHECK-32-NEXT: (field name=anyProtoComposition offset=32 // CHECK-32-NEXT: (existential_metatype size=12 alignment=4 stride=12 num_extra_inhabitants=4096 bitwise_takable=1 // CHECK-32-NEXT: (field name=metadata offset=0 // CHECK-32-NEXT: (builtin size=4 alignment=4 stride=4 num_extra_inhabitants=4096 bitwise_takable=1)) // CHECK-32-NEXT: (field name=wtable offset=4 // CHECK-32-NEXT: (builtin size=4 alignment=4 stride=4 num_extra_inhabitants=1 bitwise_takable=1)) // CHECK-32-NEXT: (field name=wtable offset=8 // CHECK-32-NEXT: (builtin size=4 alignment=4 stride=4 num_extra_inhabitants=1 bitwise_takable=1)))) // CHECK-32-NEXT: (field name=optionalAnyProtoComposition offset=44 // CHECK-32-NEXT: (single_payload_enum size=12 alignment=4 stride=12 num_extra_inhabitants=4095 bitwise_takable=1 // CHECK-32-NEXT: (case name=some index=0 offset=0 // CHECK-32-NEXT: (existential_metatype size=12 alignment=4 stride=12 num_extra_inhabitants=4096 bitwise_takable=1 // CHECK-32-NEXT: (field name=metadata offset=0 // CHECK-32-NEXT: (builtin size=4 alignment=4 stride=4 num_extra_inhabitants=4096 bitwise_takable=1)) // CHECK-32-NEXT: (field name=wtable offset=4 // CHECK-32-NEXT: (builtin size=4 alignment=4 stride=4 num_extra_inhabitants=1 bitwise_takable=1)) // CHECK-32-NEXT: (field name=wtable offset=8 // CHECK-32-NEXT: (builtin size=4 alignment=4 stride=4 num_extra_inhabitants=1 bitwise_takable=1)))) // CHECK-32-NEXT: (case name=none index=1))) // CHECK-32-NEXT: (field name=structMetatype offset=56 // CHECK-32-NEXT: (builtin size=0 alignment=1 stride=1 num_extra_inhabitants=0 bitwise_takable=1)) // CHECK-32-NEXT: (field name=optionalStructMetatype offset=56 // CHECK-32-NEXT: (single_payload_enum size=4 alignment=4 stride=4 num_extra_inhabitants=4095 bitwise_takable=1 // CHECK-32-NEXT: (case name=some index=0 offset=0 // CHECK-32-NEXT: (builtin size=4 alignment=4 stride=4 num_extra_inhabitants=4096 bitwise_takable=1)) // CHECK-32-NEXT: (case name=none index=1))) // CHECK-32-NEXT: (field name=classMetatype offset=60 // CHECK-32-NEXT: (builtin size=4 alignment=4 stride=4 num_extra_inhabitants=4096 bitwise_takable=1)) // CHECK-32-NEXT: (field name=optionalClassMetatype offset=64 // CHECK-32-NEXT: (single_payload_enum size=4 alignment=4 stride=4 num_extra_inhabitants=4095 bitwise_takable=1 // CHECK-32-NEXT: (case name=some index=0 offset=0 // CHECK-32-NEXT: (builtin size=4 alignment=4 stride=4 num_extra_inhabitants=4096 bitwise_takable=1)) // CHECK-32-NEXT: (case name=none index=1))) // CHECK-32-NEXT: (field name=abstractMetatype offset=68 // CHECK-32-NEXT: (struct size=8 alignment=4 stride=8 num_extra_inhabitants=4096 bitwise_takable=1 // CHECK-32-NEXT: (field name=t offset=0 // CHECK-32-NEXT: (builtin size=4 alignment=4 stride=4 num_extra_inhabitants=4096 bitwise_takable=1)) // CHECK-32-NEXT: (field name=u offset=4 // CHECK-32-NEXT: (builtin size=4 alignment=4 stride=4 num_extra_inhabitants=4096 bitwise_takable=1))))) 12TypeLowering10EnumStructV // CHECK-64: (struct TypeLowering.EnumStruct) // CHECK-64-NEXT: (struct size=81 alignment=8 stride=88 num_extra_inhabitants=[[PTR_XI]] bitwise_takable=1 // CHECK-64-NEXT: (field name=empty offset=0 // CHECK-64-NEXT: (no_payload_enum size=0 alignment=1 stride=1 num_extra_inhabitants=0 bitwise_takable=1)) // CHECK-64-NEXT: (field name=noPayload offset=0 // CHECK-64-NEXT: (no_payload_enum size=1 alignment=1 stride=1 num_extra_inhabitants=252 bitwise_takable=1 // CHECK-64-NEXT: (case name=A index=0) // CHECK-64-NEXT: (case name=B index=1) // CHECK-64-NEXT: (case name=C index=2) // CHECK-64-NEXT: (case name=D index=3))) // CHECK-64-NEXT: (field name=sillyNoPayload offset=1 // CHECK-64-NEXT: (multi_payload_enum size=1 alignment=1 stride=1 num_extra_inhabitants=252 bitwise_takable=1 // CHECK-64-NEXT: (case name=A index=0 offset=0 // CHECK-64-NEXT: (no_payload_enum size=0 alignment=1 stride=1 num_extra_inhabitants=0 bitwise_takable=1)) // CHECK-64-NEXT: (case name=B index=1 offset=0 // CHECK-64-NEXT: (no_payload_enum size=0 alignment=1 stride=1 num_extra_inhabitants=0 bitwise_takable=1)) // CHECK-64-NEXT: (case name=C index=2) // CHECK-64-NEXT: (case name=D index=3))) // CHECK-64-NEXT: (field name=singleton offset=8 // CHECK-64-NEXT: (reference kind=strong refcounting=native)) // CHECK-64-NEXT: (field name=singlePayload offset=16 // CHECK-64-NEXT: (single_payload_enum size=8 alignment=8 stride=8 num_extra_inhabitants=[[PTR_XI_SUB_1]] bitwise_takable=1 // CHECK-64-NEXT: (case name=Indirect index=0 offset=0 // CHECK-64-NEXT: (reference kind=strong refcounting=native)) // CHECK-64-NEXT: (case name=Nothing index=1))) // CHECK-64-NEXT: (field name=multiPayloadConcrete offset=24 // CHECK-64-NEXT: (multi_payload_enum size=8 alignment=8 stride=8 num_extra_inhabitants={{(2045|125)}} bitwise_takable=1 // CHECK-64-NEXT: (case name=Left index=0 offset=0 // CHECK-64-NEXT: (reference kind=strong refcounting=native)) // CHECK-64-NEXT: (case name=Right index=1 offset=0 // CHECK-64-NEXT: (reference kind=strong refcounting=native)) // CHECK-64-NEXT: (case name=Donkey index=2) // CHECK-64-NEXT: (case name=Mule index=3) // CHECK-64-NEXT: (case name=Horse index=4))) // CHECK-64-NEXT: (field name=multiPayloadGenericFixed offset=32 // CHECK-64-NEXT: (multi_payload_enum size=9 alignment=8 stride=16 num_extra_inhabitants=253 bitwise_takable=1 // CHECK-64-NEXT: (case name=Left index=0 offset=0 // CHECK-64-NEXT: (reference kind=strong refcounting=native)) // CHECK-64-NEXT: (case name=Right index=1 offset=0 // CHECK-64-NEXT: (reference kind=strong refcounting=native)) // CHECK-64-NEXT: (case name=Donkey index=2) // CHECK-64-NEXT: (case name=Mule index=3) // CHECK-64-NEXT: (case name=Horse index=4))) // CHECK-64-NEXT: (field name=multiPayloadGenericDynamic offset=48 // CHECK-64-NEXT: (multi_payload_enum size=9 alignment=8 stride=16 num_extra_inhabitants=253 bitwise_takable=1 // CHECK-64-NEXT: (case name=Left index=0 offset=0 // CHECK-64-NEXT: (struct size=1 alignment=1 stride=1 num_extra_inhabitants=0 bitwise_takable=1 // CHECK-64-NEXT: (field name=_value offset=0 // CHECK-64-NEXT: (builtin size=1 alignment=1 stride=1 num_extra_inhabitants=0 bitwise_takable=1)))) // CHECK-64-NEXT: (case name=Right index=1 offset=0 // CHECK-64-NEXT: (struct size=8 alignment=8 stride=8 num_extra_inhabitants=0 bitwise_takable=1 // CHECK-64-NEXT: (field name=_value offset=0 // CHECK-64-NEXT: (builtin size=8 alignment=8 stride=8 num_extra_inhabitants=0 bitwise_takable=1)))) // CHECK-64-NEXT: (case name=Donkey index=2) // CHECK-64-NEXT: (case name=Mule index=3) // CHECK-64-NEXT: (case name=Horse index=4))) // CHECK-64-NEXT: (field name=optionalOptionalRef offset=64 // CHECK-64-NEXT: (single_payload_enum size=8 alignment=8 stride=8 num_extra_inhabitants=[[PTR_XI_SUB_2:2147483645|2046|4094]] bitwise_takable=1 // CHECK-64-NEXT: (case name=some index=0 offset=0 // CHECK-64-NEXT: (single_payload_enum size=8 alignment=8 stride=8 num_extra_inhabitants=[[PTR_XI_SUB_1]] bitwise_takable=1 // CHECK-64-NEXT: (case name=some index=0 offset=0 // CHECK-64-NEXT: (reference kind=strong refcounting=native)) // CHECK-64-NEXT: (case name=none index=1))) // CHECK-64-NEXT: (case name=none index=1))) // CHECK-64-NEXT: (field name=optionalOptionalPtr offset=72 // CHECK-64-NEXT: (single_payload_enum size=9 alignment=8 stride=16 num_extra_inhabitants=0 bitwise_takable=1 // CHECK-64-NEXT: (case name=some index=0 offset=0 // CHECK-64-NEXT: (single_payload_enum size=8 alignment=8 stride=8 num_extra_inhabitants=0 bitwise_takable=1 // CHECK-64-NEXT: (case name=some index=0 offset=0 // CHECK-64-NEXT: (struct size=8 alignment=8 stride=8 num_extra_inhabitants=1 bitwise_takable=1 // CHECK-64-NEXT: (field name=_rawValue offset=0 // CHECK-64-NEXT: (builtin size=8 alignment=8 stride=8 num_extra_inhabitants=1 bitwise_takable=1)))) // CHECK-64-NEXT: (case name=none index=1))) // CHECK-64-NEXT: (case name=none index=1)))) 12TypeLowering23EnumStructWithOwnershipV // CHECK-64: (struct TypeLowering.EnumStructWithOwnership) // CHECK-64-NEXT: (struct size=25 alignment=8 stride=32 num_extra_inhabitants=254 bitwise_takable=0 // CHECK-64-NEXT: (field name=multiPayloadConcrete offset=0 // CHECK-64-NEXT: (multi_payload_enum size=9 alignment=8 stride=16 num_extra_inhabitants=254 bitwise_takable=0 // CHECK-64-NEXT: (case name=Left index=0 offset=0 // CHECK-64-NEXT: (struct size=8 alignment=8 stride=8 num_extra_inhabitants=0 bitwise_takable=0 // CHECK-64-NEXT: (field name=weakRef offset=0 // CHECK-64-NEXT: (reference kind=weak refcounting=native)))) // CHECK-64-NEXT: (case name=Right index=1 offset=0 // CHECK-64-NEXT: (struct size=8 alignment=8 stride=8 num_extra_inhabitants=0 bitwise_takable=0 // CHECK-64-NEXT: (field name=weakRef offset=0 // CHECK-64-NEXT: (reference kind=weak refcounting=native)))))) // CHECK-64-NEXT: (field name=multiPayloadGeneric offset=16 // CHECK-64-NEXT: (multi_payload_enum size=9 alignment=8 stride=16 num_extra_inhabitants=254 bitwise_takable=0 // CHECK-64-NEXT: (case name=Left index=0 offset=0 // CHECK-64-NEXT: (struct size=8 alignment=8 stride=8 num_extra_inhabitants=0 bitwise_takable=0 // CHECK-64-NEXT: (field name=weakRef offset=0 // CHECK-64-NEXT: (reference kind=weak refcounting=native)))) // CHECK-64-NEXT: (case name=Right index=1 offset=0 // CHECK-64-NEXT: (struct size=1 alignment=1 stride=1 num_extra_inhabitants=0 bitwise_takable=1 // CHECK-64-NEXT: (field name=_value offset=0 // CHECK-64-NEXT: (builtin size=1 alignment=1 stride=1 num_extra_inhabitants=0 bitwise_takable=1))))))) // CHECK-32: (struct TypeLowering.EnumStructWithOwnership) // CHECK-32-NEXT: (struct size=13 alignment=4 stride=16 num_extra_inhabitants=254 bitwise_takable=0 // CHECK-32-NEXT: (field name=multiPayloadConcrete offset=0 // CHECK-32-NEXT: (multi_payload_enum size=5 alignment=4 stride=8 num_extra_inhabitants=254 bitwise_takable=0 // CHECK-32-NEXT: (case name=Left index=0 offset=0 // CHECK-32-NEXT: (struct size=4 alignment=4 stride=4 num_extra_inhabitants=0 bitwise_takable=0 // CHECK-32-NEXT: (field name=weakRef offset=0 // CHECK-32-NEXT: (reference kind=weak refcounting=native)))) // CHECK-32-NEXT: (case name=Right index=1 offset=0 // CHECK-32-NEXT: (struct size=4 alignment=4 stride=4 num_extra_inhabitants=0 bitwise_takable=0 // CHECK-32-NEXT: (field name=weakRef offset=0 // CHECK-32-NEXT: (reference kind=weak refcounting=native)))))) // CHECK-32-NEXT: (field name=multiPayloadGeneric offset=8 // CHECK-32-NEXT: (multi_payload_enum size=5 alignment=4 stride=8 num_extra_inhabitants=254 bitwise_takable=0 // CHECK-32-NEXT: (case name=Left index=0 offset=0 // CHECK-32-NEXT: (struct size=4 alignment=4 stride=4 num_extra_inhabitants=0 bitwise_takable=0 // CHECK-32-NEXT: (field name=weakRef offset=0 // CHECK-32-NEXT: (reference kind=weak refcounting=native)))) // CHECK-32-NEXT: (case name=Right index=1 offset=0 // CHECK-32-NEXT: (struct size=1 alignment=1 stride=1 num_extra_inhabitants=0 bitwise_takable=1 // CHECK-32-NEXT: (field name=_value offset=0 // CHECK-32-NEXT: (builtin size=1 alignment=1 stride=1 num_extra_inhabitants=0 bitwise_takable=1))))))) Bo // CHECK-64: (builtin Builtin.NativeObject) // CHECK-64-NEXT: (reference kind=strong refcounting=native) // CHECK-32: (builtin Builtin.NativeObject) // CHECK-32-NEXT: (reference kind=strong refcounting=native) BO // CHECK-64: (builtin Builtin.UnknownObject) // CHECK-64-NEXT: (reference kind=strong refcounting=unknown) // CHECK-32: (builtin Builtin.UnknownObject) // CHECK-32-NEXT: (reference kind=strong refcounting=unknown) 12TypeLowering22RefersToOtherAssocTypeV // CHECK-64: (struct TypeLowering.RefersToOtherAssocType) // CHECK-64-NEXT: (struct size=8 alignment=4 stride=8 num_extra_inhabitants=0 bitwise_takable=1 // CHECK-64-NEXT: (field name=x offset=0 // CHECK-64-NEXT: (struct size=4 alignment=4 stride=4 num_extra_inhabitants=0 bitwise_takable=1 // CHECK-64-NEXT: (field name=_value offset=0 // CHECK-64-NEXT: (builtin size=4 alignment=4 stride=4 num_extra_inhabitants=0 bitwise_takable=1)))) // CHECK-64-NEXT: (field name=y offset=4 // CHECK-64-NEXT: (struct size=4 alignment=4 stride=4 num_extra_inhabitants=0 bitwise_takable=1 // CHECK-64-NEXT: (field name=_value offset=0 // CHECK-64-NEXT: (builtin size=4 alignment=4 stride=4 num_extra_inhabitants=0 bitwise_takable=1))))) // CHECK-32: (struct TypeLowering.RefersToOtherAssocType) // CHECK-32-NEXT: (struct size=8 alignment=4 stride=8 num_extra_inhabitants=0 bitwise_takable=1 // CHECK-32-NEXT: (field name=x offset=0 // CHECK-32-NEXT: (struct size=4 alignment=4 stride=4 num_extra_inhabitants=0 bitwise_takable=1 // CHECK-32-NEXT: (field name=_value offset=0 // CHECK-32-NEXT: (builtin size=4 alignment=4 stride=4 num_extra_inhabitants=0 bitwise_takable=1)))) // CHECK-32-NEXT: (field name=y offset=4 // CHECK-32-NEXT: (struct size=4 alignment=4 stride=4 num_extra_inhabitants=0 bitwise_takable=1 // CHECK-32-NEXT: (field name=_value offset=0 // CHECK-32-NEXT: (builtin size=4 alignment=4 stride=4 num_extra_inhabitants=0 bitwise_takable=1))))) 12TypeLowering18GenericOnAssocTypeVyAA13OpaqueWitnessVG // CHECK-64: (bound_generic_struct TypeLowering.GenericOnAssocType // CHECK-64-NEXT: (struct TypeLowering.OpaqueWitness)) // CHECK-64-NEXT: (struct size=8 alignment=4 stride=8 num_extra_inhabitants=0 bitwise_takable=1 // CHECK-64-NEXT: (field name=x offset=0 // CHECK-64-NEXT: (struct size=4 alignment=4 stride=4 num_extra_inhabitants=0 bitwise_takable=1 // CHECK-64-NEXT: (field name=_value offset=0 // CHECK-64-NEXT: (builtin size=4 alignment=4 stride=4 num_extra_inhabitants=0 bitwise_takable=1)))) // CHECK-64-NEXT: (field name=y offset=4 // CHECK-64-NEXT: (struct size=4 alignment=4 stride=4 num_extra_inhabitants=0 bitwise_takable=1 // CHECK-64-NEXT: (field name=_value offset=0 // CHECK-64-NEXT: (builtin size=4 alignment=4 stride=4 num_extra_inhabitants=0 bitwise_takable=1))))) // CHECK-32: (bound_generic_struct TypeLowering.GenericOnAssocType // CHECK-32-NEXT: (struct TypeLowering.OpaqueWitness)) // CHECK-32-NEXT: (struct size=8 alignment=4 stride=8 num_extra_inhabitants=0 bitwise_takable=1 // CHECK-32-NEXT: (field name=x offset=0 // CHECK-32-NEXT: (struct size=4 alignment=4 stride=4 num_extra_inhabitants=0 bitwise_takable=1 // CHECK-32-NEXT: (field name=_value offset=0 // CHECK-32-NEXT: (builtin size=4 alignment=4 stride=4 num_extra_inhabitants=0 bitwise_takable=1)))) // CHECK-32-NEXT: (field name=y offset=4 // CHECK-32-NEXT: (struct size=4 alignment=4 stride=4 num_extra_inhabitants=0 bitwise_takable=1 // CHECK-32-NEXT: (field name=_value offset=0 // CHECK-32-NEXT: (builtin size=4 alignment=4 stride=4 num_extra_inhabitants=0 bitwise_takable=1)))))
apache-2.0
daaavid/DJTutorialView
DJTutorialView/Classes/DJTutorialView.swift
1
13930
// // DJTutorialView.swift // DJTutorialView // // Created by david on 2/5/17. // Copyright © 2017 david. All rights reserved. // import UIKit private let IPAD = UIDevice.current.userInterfaceIdiom == .pad /** Adopt this protocol to be notified of the following: - `func djTutorialView(view: DJTutorialView, willStepWith step: DJTutorialViewStep, atIndex index: Int)` - `func djTutorialView(view: DJTutorialView, didStepWith step: DJTutorialViewStep, atIndex index: Int)` Pretty self-explanatory, right? :^) */ public protocol DJTutorialViewDelegate { /** Called just before performing the step. Use the index or tutorial step properties to determine which step will be called. Use the index and view.numberOfSteps to determine progress. - parameter step: The step that will be called - parameter index: The index of the step */ func djTutorialView(view: DJTutorialView, willStepWith step: DJTutorialViewStep, atIndex index: Int) /** Called just after performing the step. Use the index or tutorial step properties to determine which step was just called. Use the index and view.numberOfSteps to determine progress. - parameter step: The step that was just called - parameter index: The index of the step */ func djTutorialView(view: DJTutorialView, didStepWith step: DJTutorialViewStep, atIndex index: Int) } open class DJTutorialView: UIView { public var overlayView: UIView! public var leftGesture: UIGestureRecognizer! public var rightGesture: UIGestureRecognizer! public var tapGesture: UITapGestureRecognizer! public var delegate: DJTutorialViewDelegate? /// The current step in the tutorial. public var currentStep: DJTutorialViewStep? /// Read-only -- The number of steps in the tutorial. public var numberOfSteps: Int { return self.tutorialSteps.count } /// Array of steps in the tutorial. public var tutorialSteps = [DJTutorialViewStep]() { didSet { self.didSet(steps: self.tutorialSteps) } } // MARK: - UI /// Close button. Use `showsCloseButton` to hide or show this button. Value is nil if showsCloseButton == true. public var closeButton: UIButton? /// Set to add or remove close button. public var showsCloseButton: Bool = true { didSet { self.didSet(showsCloseButton: self.showsCloseButton) } } /// Tutorial page control public var pageControl: UIPageControl = UIPageControl() /// Inits with init(frame: view.frame) and adds self to view. public convenience init(view: UIView) { self.init(frame: view.frame) view.addSubview(self) } override public init(frame: CGRect) { super.init(frame: frame) self.sharedInit() } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) self.sharedInit() } /// Convenience function for TutorialStep's `callBefore` and `callAfter` private func performAfter(_ interval: TimeInterval, action:@escaping () -> ()) { DispatchQueue.main.asyncAfter(deadline: .now() + interval) { action() } } /// Called during both init(frame: CGRect) and init?(coder aDecoder: NSCoder). Sets up the view. Override if you want, but remember to call super.sharedInit(). public func sharedInit() { self.isHidden = true self.showsCloseButton = true self.backgroundColor = UIColor.clear self.overlayView = UIView(frame: self.frame) self.overlayView.backgroundColor = UIColor.black self.overlayView.alpha = 0.8 self.overlayView.isHidden = true self.addSubview(overlayView) self.setupPageControl() self.setupGestures() } public func start() { self.alpha = 0 self.isHidden = false self.overlayView.isHidden = false self.superview?.bringSubview(toFront: self) UIView.animate(withDuration: 0.25) { self.alpha = 1 } } public func close() { UIView.animate(withDuration: 1, animations: { self.alpha = 0 }, completion: { finished in self.moveToStep(index: 0) self.isHidden = true }) } } // Steps public extension DJTutorialView { public func moveToNextStep() { let index = self.currentStep?.index ?? -1 self.moveToStep(index: index + 1) } public func moveToPreviousStep() { let index = self.currentStep?.index ?? 1 self.moveToStep(index: index - 1) } public func moveToStep(step: DJTutorialViewStep) { if let index = step.index { self.moveToStep(index: index) } } public func moveToStep(index: Int) { guard let current = self.currentStep else { if let first = self.tutorialSteps.first { self.currentStep = first self.moveToStep(index: index) } return } guard let next = self.tutorialSteps[safe: index] else { self.close() return } self.delegate?.djTutorialView(view: self, willStepWith: next, atIndex: index) UIView.animate(withDuration: 0.5, animations: { current.label.alpha = 0 }) { finished in self.setupMask(for: next) self.currentStep = next self.pageControl.currentPage = index self.delegate?.djTutorialView(view: self, didStepWith: next, atIndex: index) UIView.animate(withDuration: 0.25) { next.label.alpha = 1 } } } } // Setup public extension DJTutorialView { /// Called during sharedInit to setup page control. Remember to call `super`, otherwise `pageControl` will be nil. public func setupPageControl() { let control = self.pageControl self.addSubview(control) // let constraintInfo: [(NSLayoutAttribute, CGFloat)] = [ // (.bottom, -24), (.centerX, 0) // ] // // constraintInfo.forEach { // let (attribute, constant) = $0 // let constraint = NSLayoutConstraint( // item: control, // attribute: attribute, // relatedBy: .equal, // toItem: self, // attribute: attribute, // multiplier: 1, // constant: constant // ) // // self.addConstraint(constraint) // constraint.isActive = true // } } /// Called during sharedInit to setup swipe and tap gestures. Remember to call `super` if you want to keep these gestures. public func setupGestures() { let left = UISwipeGestureRecognizer(target: self, action: #selector(self.moveToNextStep)) left.direction = .left let right = UISwipeGestureRecognizer(target: self, action: #selector(self.moveToPreviousStep)) right.direction = .right let tap = UITapGestureRecognizer(target: self, action: #selector(self.moveToNextStep)) self.addGestureRecognizer(left) self.addGestureRecognizer(right) self.addGestureRecognizer(tap) self.leftGesture = left self.rightGesture = right self.tapGesture = tap } public func setupMask(for step: DJTutorialViewStep) { let maskPath = UIBezierPath(rect: self.frame) if let view = step.view { let cutoutPath = UIBezierPath(roundedRect: view.frame, cornerRadius: 4.0) maskPath.append(cutoutPath) } let maskLayer = CAShapeLayer() maskLayer.backgroundColor = UIColor.black.cgColor maskLayer.path = maskPath.cgPath; maskLayer.fillRule = kCAFillRuleEvenOdd self.overlayView.layer.mask = maskLayer } override open func didMoveToSuperview() { super.didMoveToSuperview() self.setupConstraints() } public func setupConstraints() { guard let superview = self.superview else { return } self.translatesAutoresizingMaskIntoConstraints = false let attributes: [NSLayoutAttribute] = [.top, .leading, .trailing, .bottom] attributes.forEach { attribute in let constraint = NSLayoutConstraint( item: self, attribute: attribute, relatedBy: .equal, toItem: superview, attribute: attribute, multiplier: 1, constant: 0 ) superview.addConstraint(constraint) constraint.isActive = true } } } //Step Constraints public extension DJTutorialView { /// Called when a step is reached. Sets a height constraint based on the label text, then width constraint (0.8x width if iphone, 0.6x width if ipad) and finally calls either `setupCenterLabelConstraints` or `setupRelativeLabelConstraints` to determine where to place the label -- depending on if there's a view or nothing to highlight for the step. public func setupLabelConstraints(for step: DJTutorialViewStep) { let multiplier: CGFloat = IPAD ? 0.6 : 0.8 let label = step.label let widthConstraint = NSLayoutConstraint( item: label, attribute: .width, relatedBy: .equal, toItem: self, attribute: .width, multiplier: multiplier, constant: 0 ) label.addConstraint(widthConstraint) widthConstraint.isActive = true if step.view == nil { } } /// Called when tutorial step is reached and tutorial step view is nil. Sets up center constraints for label. public func setupCenterLabelConstraints(for step: DJTutorialViewStep) { let label = step.label let center = NSLayoutConstraint( item: label, attribute: .centerX, relatedBy: .equal, toItem: self, attribute: .centerX, multiplier: 1, constant: 0 ) label.addConstraint(center) center.isActive = true } /// Called when tutorial step is reached and tutorial step view is not nil. Tries to determine the best label position in relation to tutorial step view and sets up relative constraints for label. public func setupRelativeLabelConstraints(for step: DJTutorialViewStep, width: CGFloat, view: UIView) { guard let view = step.view else { return } let originY = view.convert(view.frame.origin, to: nil).y let label = step.label let viewHeight = view.frame.height let height = label.height(width: width) let availableBottomSpace: CGFloat = { let combined = originY + viewHeight let available = self.frame.height - combined print("canPlaceAtBottom available \(available)") return available }() let canPlaceAtBottom = height < availableBottomSpace let availableTopSpace: CGFloat = originY let canPlaceAtTop = originY > height + 8 var constraint: NSLayoutConstraint! if availableBottomSpace > availableTopSpace && canPlaceAtBottom && view.isVisible { print("label placed underneath view") constraint = NSLayoutConstraint( item: label, attribute: .top, relatedBy: .equal, toItem: self, attribute: .top, multiplier: 1, constant: originY + view.frame.height + 8 ) } else if availableTopSpace > availableBottomSpace && canPlaceAtTop && view.isVisible { constraint = NSLayoutConstraint( item: label, attribute: .top, relatedBy: .equal, toItem: self, attribute: .top, multiplier: 1, constant: originY - height ) } else { constraint = NSLayoutConstraint( item: label, attribute: .bottom, relatedBy: .equal, toItem: self, attribute: .bottom, multiplier: 1, constant: -16 ) } label.addConstraint(constraint) constraint.isActive = true } } // DidSet public extension DJTutorialView { /// Called when `showsCloseButton` is set. If showsCloseButton == true && closeButton == nil, adds a close button to the view that closes out the tutorial. Else, removes the close button if there is one. public func didSet(showsCloseButton: Bool) { if showsCloseButton && self.closeButton == nil { let button = UIButton() button.setTitle("×", for: .normal) button.titleLabel?.font = UIFont(name: "HelveticaNeue-Light", size: 40)! button.frame = CGRect(x: 8, y: 16, width: 40, height: 40) self.addSubview(button) self.closeButton = button } else { self.closeButton?.removeFromSuperview() self.closeButton = nil } } /// Called when `DJTutorialViewStep` is called. Sets the tutorial step's index to the index of where it is in `tutorialSteps` public func didSet(steps: [DJTutorialViewStep]) { steps.forEach { $0.index = steps.index(of: $0) } } } // AddTutorialStep public extension DJTutorialView { /// Used to add a tutorial step. Make a TutorialStep and pass it in to this function. public func addTutorialStep(step: DJTutorialViewStep) { self.tutorialSteps.append(step) } /** Used to add a tutorial step. It'd probably be better to use `addTutorialStep(step: DJTutorialViewStep)`, but I'm giving you some options! Use whichever you prefer :^) Pass in a title, message, and optionally pass in a callBefore / callAfter to run a function x seconds before / after the step is reached. - parameter view: The view to highlight during this step - parameter title: The title of this step, displayed during this step - parameter message: The message of this step, displayed during this step - parameter callBefore: An optional function to call a specified interval before starting the step. Delays the step, so don't place too large of an interval. Mostly used to set up some UI before starting the step. - parameter callAfter: An optional function to call a specified interval after starting the step. Used to clean up after the step completes. */ public func addTutorialStep( view: UIView?, title: String, message: String, callBefore:((_ interval: TimeInterval) -> ())? = nil, callAfter:((_ interval: TimeInterval) -> ())? = nil) { let step = DJTutorialViewStep( view: view, title: title, message: message, callBefore: callBefore, callAfter: callAfter ) self.addTutorialStep(step: step) } }
mit
nathawes/swift
test/Driver/Dependencies/malformed-fine.swift
2
3450
// RUN: %empty-directory(%t) // RUN: cp -r %S/Inputs/malformed-after-fine/* %t // RUN: touch -t 201401240005 %t/*.swift // Generate the build record... // RUN: cd %t && %swiftc_driver -c -driver-use-frontend-path "%{python.unquoted};%S/Inputs/update-dependencies.py;%swift-dependency-tool" -output-file-map %t/output.json -incremental -driver-always-rebuild-dependents ./main.swift ./other.swift -module-name main -j1 -v // ...then reset the .swiftdeps files. // RUN: cp -r %S/Inputs/malformed-after-fine/*.swiftdeps %t // RUN: cd %t && %swiftc_driver -c -driver-use-frontend-path "%{python.unquoted};%S/Inputs/update-dependencies.py;%swift-dependency-tool" -output-file-map %t/output.json -incremental -driver-always-rebuild-dependents ./main.swift ./other.swift -module-name main -j1 -v 2>&1 | %FileCheck -check-prefix=CHECK-FIRST %s // CHECK-FIRST-NOT: warning // CHECK-FIRST-NOT: Handled // RUN: touch -t 201401240006 %t/other.swift // RUN: cd %t && %swiftc_driver -c -driver-use-frontend-path "%{python.unquoted};%S/Inputs/update-dependencies.py;%swift-dependency-tool" -output-file-map %t/output.json -incremental -driver-always-rebuild-dependents ./main.swift ./other.swift -module-name main -j1 -v 2>&1 | %FileCheck -check-prefix=CHECK-SECOND %s // CHECK-SECOND: Handled other.swift // CHECK-SECOND: Handled main.swift // RUN: touch -t 201401240007 %t/other.swift // RUN: cd %t && %swiftc_driver -c -driver-use-frontend-path "%{python.unquoted};%S/Inputs/update-dependencies.py;%swift-dependency-tool" -output-file-map %t/output.json -incremental -driver-always-rebuild-dependents ./main.swift ./other.swift -module-name main -j1 -v 2>&1 | %FileCheck -check-prefix=CHECK-THIRD %s // CHECK-THIRD: Handled main.swift // CHECK-THIRD: Handled other.swift // RUN: %empty-directory(%t) // RUN: cp -r %S/Inputs/malformed-after-fine/* %t // RUN: touch -t 201401240005 %t/*.swift // Generate the build record... // RUN: cd %t && %swiftc_driver -c -driver-use-frontend-path "%{python.unquoted};%S/Inputs/update-dependencies.py;%swift-dependency-tool" -output-file-map %t/output.json -incremental -driver-always-rebuild-dependents ./main.swift ./other.swift -module-name main -j1 -v // ...then reset the .swiftdeps files. // RUN: cp -r %S/Inputs/malformed-after-fine/*.swiftdeps %t // RUN: cd %t && %swiftc_driver -c -driver-use-frontend-path "%{python.unquoted};%S/Inputs/update-dependencies.py;%swift-dependency-tool" -output-file-map %t/output.json -incremental -driver-always-rebuild-dependents ./main.swift ./other.swift -module-name main -j1 -v 2>&1 | %FileCheck -check-prefix=CHECK-FIRST %s // RUN: touch -t 201401240006 %t/main.swift // RUN: cd %t && %swiftc_driver -c -driver-use-frontend-path "%{python.unquoted};%S/Inputs/update-dependencies.py;%swift-dependency-tool" -output-file-map %t/output.json -incremental -driver-always-rebuild-dependents ./main.swift ./other.swift -module-name main -j1 -v 2>&1 | %FileCheck -check-prefix=CHECK-FOURTH %s // RUN: touch -t 201401240007 %t/main.swift // RUN: cd %t && %swiftc_driver -c -driver-use-frontend-path "%{python.unquoted};%S/Inputs/update-dependencies.py;%swift-dependency-tool" -output-file-map %t/output.json -incremental -driver-always-rebuild-dependents ./main.swift ./other.swift -module-name main -j1 -v 2>&1 | %FileCheck -check-prefix=CHECK-FOURTH %s // CHECK-FOURTH-NOT: Handled other.swift // CHECK-FOURTH: Handled main.swift // CHECK-FOURTH-NOT: Handled other.swift
apache-2.0
ghotjunwoo/Tiat
EntireChatViewController.swift
1
1372
// // EntireChatViewController.swift // Tiat // // Created by 이종승 on 2016. 10. 2.. // Copyright © 2016년 JW. All rights reserved. // import UIKit import Firebase class EntireChatViewController: UIViewController { let userUid = FIRAuth.auth()?.currentUser!.uid @IBOutlet weak var TopBar: UINavigationItem! override func viewDidLoad() { super.viewDidLoad() let button = UIButton(type: .custom) button.setTitle("Button", for: UIControlState.normal) button.setTitleColor(.black, for: .normal) button.setTitleColor(.gray, for: .selected) button.addTarget(self, action: #selector(EntireChatViewController.showChatViewController), for: UIControlEvents.touchUpInside) let userRef = FIRDatabase.database().reference().child("users/\(userUid!)") self.navigationItem.titleView = button userRef.child("name").observe(.value) { (snap: FIRDataSnapshot) in button.setTitle((snap.value as! String).description, for: .normal) button.setTitle((snap.value as! String).description, for: .selected) } print(userUid) } func showChatViewController() { performSegue(withIdentifier: "toChatLogController", sender: self) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } }
gpl-3.0
DannyVancura/SwifTrix
SwifTrix/Examples/iOS/FormFillingDatabaseExample/FormFillingDatabaseExample/FirstViewController.swift
1
5078
// // FirstViewController.swift // FormFillingDatabaseExample // // The MIT License (MIT) // // Copyright © 2015 Daniel Vancura // // 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 import SwifTrix class FirstViewController: UIViewController, STFormFillControllerDelegate { private var formFillController: STFormFillController? override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) self.formFillController?.formFields = self.createEmptyFormFields() } override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if segue.identifier == "embedFormFillController" { // Get reference to the form fill controller in the container ver guard let formFillController = segue.destinationViewController as? STFormFillController else { return } self.formFillController = formFillController self.formFillController?.delegate = self } } // MARK: - Sample implementation of some table view cells /** Creates a set of four form fields */ private func createEmptyFormFields() -> [STFormField] { // Create an ordered array of form fields var formFields: [STFormField] = [] formFields.append(STFormField(label: "Name", isRequired: true, dataType: .UnformattedText)) formFields.append(STFormField(label: "E-Mail", isRequired: true, dataType: .EMail)) // A form field with a very simple "value selection" prototype formFields.append(STFormField(label: "Birth date", isRequired: false, dataType: .Date, additionalRequirements: [], customFormFieldAction: { (inout formField: STFormField) -> Void in formField.value="1/2/34" })) // A form field with custom additional requirements for unformatted text formFields.append(STFormField(label: "Gender", isRequired: false, dataType: .UnformattedText, additionalRequirements: [({ return $0 == "Male" || $0 == "Female" }, "You were supposed to enter 'Male' or 'Female'")])) return formFields } // MARK: - Implementation for the save- and cancel- button actions func formFillController(controller: STFormFillController, didSave savedItems: [STFormField]?) { // Save the entries in a new object in the database if let formFilling: FormFilling = STDatabase.SharedDatabase!.createObjectNamed("FormFilling") { formFilling.name = savedItems?[0].value formFilling.eMail = savedItems?[1].value if let dateString = savedItems?[2].value { formFilling.date = NSDateFormatter().dateFromString(dateString) } formFilling.gender = savedItems?[3].value STDatabase.SharedDatabase!.save() } // Clear the form fields by overwriting them with new ones self.formFillController?.formFields = self.createEmptyFormFields() } func formFillControllerDidCancel(controller: STFormFillController) { // Clear the form fields by overwriting them with new ones self.formFillController?.formFields = self.createEmptyFormFields() } // MARK: - Implementation to load your own table view cell style func formFillController(controller: STFormFillController, shouldUseNibForFormField formField: STFormField) -> UINib { return UINib(nibName: "CustomFormFillCell", bundle: nil) } func formFillController(controller: STFormFillController, shouldUseReuseIdentifierForFormField formField: STFormField) -> String { return "example.cell.reuseID" } }
mit
DrGo/LearningSwift
PLAYGROUNDS/LSB_D003_NamedParameters.playground/section-2.swift
2
1430
import UIKit /* // Named Parameters // // Based on: // https://skillsmatter.com/skillscasts/6142-swift-beauty-by-default /===================================*/ /*------------------------------------/ // Functions: Unnamed // // Looks like C /------------------------------------*/ func add(x: Int, y: Int) -> Int { return x + y } add(1, 2) /*------------------------------------/ // Methods: First is Unnamed, // Rest Named // // Because of Objective-C /------------------------------------*/ class Adder { class func addX(x:Int, y:Int) -> Int { return x + y } func addX(x: Int, y:Int) -> Int { return x + y } } Adder.addX(1, y: 2) Adder().addX(1, y: 2) /*------------------------------------/ // Initializer: Named // // Because of Objective-C /------------------------------------*/ class Rect { var x, y, width, height: Double init(x: Double, y: Double, width: Double, height: Double) { self.x = x self.y = y self.width = width self.height = height } } Rect(x: 0, y: 0, width: 100, height: 100) /*-----------------------------------------/ // Parameters with default value: Named // // Makes optional parameter clearer /-----------------------------------------*/ func greeting(name: String, yell: Bool = false) -> String { let greet = "Hello, \(name)" return yell ? greet.uppercaseString : greet } greeting("Jim") greeting("Jim", yell: true)
gpl-3.0
Chantalisima/Spirometry-app
EspiroGame/UserResultsViewController.swift
1
6860
// // UserResultsViewController.swift // EspiroGame // // Created by Chantal de Leste on 28/4/17. // Copyright © 2017 Universidad de Sevilla. All rights reserved. // import UIKit import CoreData class UserResultsViewController: UIViewController { @IBOutlet weak var lineChart: LineChart! @IBAction func dayButton(_ sender: Any) { setChartDay() } @IBAction func weekButton(_ sender: Any) { setChartWeek() } @IBAction func monthButton(_ sender: Any) { setChartMonth() } @IBAction func yearButton(_ sender: Any) { setChartYear() } var names = ["FVC","FEV1","ratio"] override func viewDidLoad() { super.viewDidLoad() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } private func setChartDay(){ let appDelegate = UIApplication.shared.delegate as! AppDelegate let context = appDelegate.persistentContainer.viewContext let request: NSFetchRequest<Test> = Test.fetchRequest() let date = Date() let calendar = Calendar.current var points: [CGPoint] = [] do{ let searchResult = try context.fetch(request) if searchResult.count > 0 { for obj in searchResult { if(Int(obj.day) == calendar.component(.day, from: date) && Int(obj.year) == calendar.component(.year, from: date) && Int(obj.month) == calendar.component(.month, from: date) ){ points.append(CGPoint(x: Double(obj.hour), y: Double(obj.fev1))) } } } }catch{ print("Error") } lineChart.xMin = 0 lineChart.xMax = 24 lineChart.yMin = 0 lineChart.yMax = 6 lineChart.deltaX = 1 lineChart.deltaY = 1 if points.count != 0 { lineChart.plot(points) lineChart.layoutSubviews() } } private func setChartWeek(){ let appDelegate = UIApplication.shared.delegate as! AppDelegate let context = appDelegate.persistentContainer.viewContext let request: NSFetchRequest<Test> = Test.fetchRequest() let date = Date() let calendar = Calendar.current var points: [CGPoint] = [] do{ let searchResult = try context.fetch(request) if searchResult.count > 0 { for obj in searchResult { if(Int(obj.day) <= calendar.component(.day, from: date) && Int(obj.day)>(calendar.component(.day, from: date)-7) && Int(obj.year) == calendar.component(.year, from: date) && Int(obj.month) == calendar.component(.month, from: date) ){ points.append(CGPoint(x: Double(obj.day), y: Double(obj.fev1))) print(points) } } } }catch{ print("Error") } lineChart.xMin = 1 lineChart.xMax = (points.last?.x)! lineChart.yMin = 0 lineChart.yMax = 6 lineChart.deltaX = 1 lineChart.deltaY = 1 if points.count != 0 { lineChart.plot(points) lineChart.layoutSubviews() } } private func setChartMonth(){ let appDelegate = UIApplication.shared.delegate as! AppDelegate let context = appDelegate.persistentContainer.viewContext let request: NSFetchRequest<Test> = Test.fetchRequest() let date = Date() let calendar = Calendar.current var points: [CGPoint] = [] do{ let searchResult = try context.fetch(request) if searchResult.count > 0 { for obj in searchResult { if( Int(obj.year) == calendar.component(.year, from: date) && Int(obj.month) == calendar.component(.month, from: date) ){ points.append(CGPoint(x: Double(obj.day), y: Double(obj.fev1))) print(points) } } } }catch{ print("Error") } lineChart.xMin = 0 lineChart.xMax = CGFloat(daysOfAMonth()) print("days of a month:\(daysOfAMonth())") lineChart.yMin = 0 lineChart.yMax = 6 lineChart.deltaX = 1 lineChart.deltaY = 1 if points.count != 0 { lineChart.plot(points) lineChart.layoutSubviews() } } private func setChartYear(){ let appDelegate = UIApplication.shared.delegate as! AppDelegate let context = appDelegate.persistentContainer.viewContext let request: NSFetchRequest<Test> = Test.fetchRequest() let date = Date() let calendar = Calendar.current var points: [CGPoint] = [] do{ let searchResult = try context.fetch(request) if searchResult.count > 0 { for obj in searchResult { if(Int(obj.year) == calendar.component(.year, from: date) ){ if let date1 = obj.date { if let day = calendar.ordinality(of: .day, in: .year, for: date1 as Date){ points.append(CGPoint(x: Double(day), y: Double(obj.fev1))) print(points) } } } } } }catch{ print("Error") } lineChart.xMin = 1 lineChart.xMax = 356 lineChart.yMin = 0 lineChart.yMax = 6 lineChart.deltaX = 15 lineChart.deltaY = 1 if points.count != 0 { lineChart.plot(points) lineChart.layoutSubviews() } } private func daysOfAMonth() -> Int { let cal = Calendar(identifier: .gregorian) let monthRange = cal.range(of: .day, in: .month, for: Date())! return monthRange.count } private func dayOfAYear() -> Int { let date = Date() // now let cal = Calendar.current return cal.ordinality(of: .day, in: .year, for: date)! } private func captureTableView(sender: UIView){ let image: UIImage = UIImage.imageWithView(view: lineChart) } } extension UIImage { class func imageWithView(view: UIView) -> UIImage { UIGraphicsBeginImageContextWithOptions(view.bounds.size, view.isOpaque, 0.0) view.drawHierarchy(in: view.bounds, afterScreenUpdates: true) let img = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return img! } }
apache-2.0
kagenZhao/cnBeta
iOS/CnBeta/Foundation Components/Nib Bridge/NibLoadable.swift
1
2802
// // NibLoadable.swift // NibLoadable // // Created by Domas on 10/02/2017. // Copyright © 2016 Trafi. All rights reserved. // import UIKit /** `NibLoadable` helps you reuse views created in .xib files. # Reference only from code Setup class by conforming to `NibLoadable`: class MyView: UIView, NibLoadable {} Get the view loaded from nib with a one-liner: let myView = MyView.fromNib() Setup like this will look for a file named "MyView.xib" in your project and load the view that is of type `MyView`. *Optionally* provide custom nib name (defaults to type name): class var nibName: String { return "MyCustomView" } # Refencing from IB To reference view from another .xib or .storyboard file simply subclass `NibView`: class MyView: NibView {} If subclassing is **not an option** override `awakeAfter(using:)` with a call to `nibLoader`: class MyView: SomeBaseView, NibLoadable { open override func awakeAfter(using aDecoder: NSCoder) -> Any? { return nibLoader.awakeAfter(using: aDecoder, super.awakeAfter(using: aDecoder)) } } # @IBDesignable referencing from IB To see live updates and get intrinsic content size of view reference simply subclass `NibView` with `@IBDesignable` attribute: @IBDesignable class MyView: NibView {} If subclassing is **not an option** override functions of the view with calls to `nibLoader`: @IBDesignable class MyView: SomeBaseView, NibLoadable { open override func awakeAfter(using aDecoder: NSCoder) -> Any? { return nibLoader.awakeAfter(using: aDecoder, super.awakeAfter(using: aDecoder)) } #if TARGET_INTERFACE_BUILDER public override init(frame: CGRect) { super.init(frame: frame) nibLoader.initWithFrame() } public required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } open override func prepareForInterfaceBuilder() { super.prepareForInterfaceBuilder() nibLoader.prepareForInterfaceBuilder() } open override func setValue(_ value: Any?, forKeyPath keyPath: String) { super.setValue(value, forKeyPath: keyPath) nibLoader.setValue(value, forKeyPath: keyPath) } #endif } */ public protocol NibLoadable: class { static var nibName: String { get } } // MARK: - From Nib public extension NibLoadable where Self: UIView { static var nibName: String { return String(describing: self) } static func fromNib() -> Self { guard let nib = Bundle(for: self).loadNibNamed(nibName, owner: nil, options: nil) else { fatalError("Failed loading the nib named \(nibName) for 'NibLoadable' view of type '\(self)'.") } guard let view = (nib.first { $0 is Self }) as? Self else { fatalError("Did not find 'NibLoadable' view of type '\(self)' inside '\(nibName).xib'.") } return view } }
mit
liuchuo/iOS9-practise
Todo/Todo/TodoModel.swift
1
436
// // TodoModel.swift // Todo // // Created by ChenXin on 16/3/9. // Copyright © 2016年 ChenXin. All rights reserved. // import UIKit class TodoModel: NSObject { var id: String var image: String var title: String var date: NSDate init (id: String, image: String, title: String, date: NSDate) { self.id = id self.image = image self.title = title self.date = date } }
gpl-3.0
JTWang4778/LearningSwiftDemos
15-UICollectionView/15-UICollectionView/AppDelegate.swift
1
2181
// // AppDelegate.swift // 15-UICollectionView // // Created by 王锦涛 on 2017/5/25. // Copyright © 2017年 JTWang. 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:. } }
mit
gnachman/iTerm2
sources/WinSizeController.swift
2
6678
// // WinSizeControllr.swift // iTerm2SharedARC // // Created by George Nachman on 5/27/22. // import Foundation @objc(iTermWinSizeControllerDelegate) protocol WinSizeControllerDelegate { func winSizeControllerIsReady() -> Bool @objc(winSizeControllerSetGridSize:viewSize:scaleFactor:) func winSizeControllerSet(size: VT100GridSize, viewSize: NSSize, scaleFactor: CGFloat) } @objc(iTermWinSizeController) class WinSizeController: NSObject { private struct Request: Equatable, CustomDebugStringConvertible { static func == (lhs: WinSizeController.Request, rhs: WinSizeController.Request) -> Bool { return (VT100GridSizeEquals(lhs.size, rhs.size) && lhs.viewSize == rhs.viewSize && lhs.scaleFactor == rhs.scaleFactor) } var size: VT100GridSize var viewSize: NSSize var scaleFactor: CGFloat var regular: Bool // false for the first resize of a jiggle static var defaultRequest: Request { return Request(size: VT100GridSizeMake(80, 25), viewSize: NSSize(width: 800, height: 250), scaleFactor: 2.0, regular: true) } func sanitized(_ last: Request?) -> Request { if scaleFactor < 1 { return Request(size: size, viewSize: viewSize, scaleFactor: last?.scaleFactor ?? 2, regular: regular) } return self } var debugDescription: String { return "<Request size=\(size) viewSize=\(viewSize) scaleFactor=\(scaleFactor) regular=\(regular)>" } } private var queue = [Request]() private var notBefore = TimeInterval(0) private var lastRequest: Request? private var deferCount = 0 { didSet { if deferCount == 0 { dequeue() } } } @objc weak var delegate: WinSizeControllerDelegate? // Cause the slave to receive a SIGWINCH and change the tty's window size. If `size` equals the // tty's current window size then no action is taken. // Returns false if it could not be set because we don't yet have a file descriptor. Returns true if // it was either set or nothing was done because the value didn't change. // NOTE: maybeScaleFactor will be 0 if the session is not attached to a window. For example, if // a different space is active. @discardableResult @objc(setGridSize:viewSize:scaleFactor:) func set(size: VT100GridSize, viewSize: NSSize, scaleFactor: CGFloat) -> Bool { set(Request(size: size, viewSize: viewSize, scaleFactor: scaleFactor, regular: true)) } // Doesn't change the size. Remembers the initial size to avoid unnecessary ioctls in the future. @objc func setInitialSize(_ size: VT100GridSize, viewSize: NSSize, scaleFactor: CGFloat) { guard lastRequest == nil else { DLog("Already have initial size") return } lastRequest = Request(size: size, viewSize: viewSize, scaleFactor: scaleFactor, regular: true) } @objc func forceJiggle() { DLog("Force jiggle") reallyJiggle() } @objc func jiggle() { DLog("Jiggle") guard queue.isEmpty else { DLog("Queue empty") return } reallyJiggle() } private func reallyJiggle() { var base = lastRequest ?? Request.defaultRequest var adjusted = base adjusted.size = VT100GridSizeMake(base.size.width + 1, base.size.height) adjusted.regular = false set(adjusted) base.regular = true set(base) } @objc func check() { dequeue() } @objc static func batchDeferChanges(_ controllers: [WinSizeController], closure: () -> ()) { for controller in controllers { controller.deferCount += 1 } closure() for controller in controllers { controller.deferCount -= 1 } } @objc func deferChanges(_ closure: () -> ()) { deferCount += 1 closure() deferCount -= 1 } @discardableResult private func set(_ request: Request) -> Bool { DLog("set \(request)") guard delegate?.winSizeControllerIsReady() ?? false else { DLog("delegate unready") return false } if request.regular && (queue.last?.regular ?? false) { DLog("Replace last request \(String(describing: queue.last))") queue.removeLast() } if !request.regular, let i = queue.firstIndex(where: { !$0.regular }) { DLog("Remove up to previously added jiggle in queue \(queue) at index \(i)") queue.removeFirst(i + 1) DLog("\(queue)") } let sanitized = request.sanitized(request) lastRequest = sanitized queue.append(sanitized) dequeue() return true } private var shouldWait: Bool { return Date.timeIntervalSinceReferenceDate < notBefore || deferCount > 0 } private func dequeue() { guard !shouldWait else { DLog("too soon to dequeue or resizing is deferred") return } guard delegate?.winSizeControllerIsReady() ?? false else { DLog("delegate unready") return } guard let request = get() else { DLog("queue empty") return } DLog("set window size to \(request)") let delay = TimeInterval(0.2) notBefore = Date.timeIntervalSinceReferenceDate + delay DLog("notBefore set to \(notBefore)") delegate?.winSizeControllerSet(size: request.size, viewSize: request.viewSize, scaleFactor: request.scaleFactor) DispatchQueue.main.asyncAfter(deadline: .now() + delay) { [weak self] in DLog("Delay finished") self?.dequeue() } } private func get() -> Request? { guard let result = queue.first else { return nil } queue.removeFirst() return result } } extension VT100GridSize: CustomDebugStringConvertible { public var debugDescription: String { return VT100GridSizeDescription(self) } }
gpl-2.0
kstaring/swift
validation-test/compiler_crashers_fixed/25392-swift-patternbindingdecl-setpattern.swift
11
434
// This source file is part of the Swift.org open source project // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // RUN: not %target-swift-frontend %s -parse var f{for{{}:{{let c{{}func a{let a{}}}}a
apache-2.0
acastano/swift-bootstrap
userinterfacekit/Unit Tests/Common/Test Cases/Utils/Extensions/UICollectionView+UtilsTests.swift
1
389
import XCTest class UICollectionViewUtilsTests: XCTestCase { override func setUp() { super.setUp() } override func tearDown() { super.tearDown() } func testExample() { } func testPerformanceExample() { self.measure { } } }
apache-2.0
johngoren/podcast-brimstone
PBC Swift/PlayViewController.swift
1
9768
// // PlayViewController.swift // PBC Swift // // Created by John Gorenfeld on 6/4/14. // Copyright (c) 2014 John Gorenfeld. All rights reserved. // import UIKit import AVFoundation typealias Seconds = Float protocol RadioPlayerDelegate { func start(url: NSURL, sender: PlayViewController) func pause() func setNewTime(position: Float) func currentSeconds() -> Float? func duration() -> Float? } enum playButtonStatus { case Playing case Paused } enum menuStatus { case Open case Closed } class PlayViewController: UIViewController { let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate let notificationCenter = NSNotificationCenter.defaultCenter() var delegate:Radio! var currentShow:Show? var duration:Float? var buttonState:playButtonStatus = playButtonStatus.Playing var menuState:menuStatus = menuStatus.Closed var imagePause = UIImage(named: "apple-pause-icon")! var imagePlay = UIImage(named: "apple-play-icon")! var alertController:UIAlertController? var websiteURL:NSURL! var subscribeURL:NSURL? var contactURL:NSURL? var shareURL:NSURL! @IBOutlet weak var ActivityIndicator: UIActivityIndicatorView! @IBOutlet weak var LabelDate: UILabel! @IBOutlet weak var LabelTitle: UILabel! @IBOutlet weak var LabelDescription: UILabel! @IBOutlet weak var Timecode: UILabel! @IBOutlet weak var Remaining: UILabel! @IBOutlet weak var slider: UISlider! @IBAction func slide() { var sliderPosition = slider!.value delegate?.setNewTime(sliderPosition) } @IBOutlet weak var pause: UIButton! override func viewDidLoad() { super.viewDidLoad() self.navigationController?.setNavigationBarHidden(false, animated: true) if let currentShow = currentShow { LabelTitle.text = currentShow.title LabelDate.text = currentShow.getFriendlyDate() LabelDescription.text = currentShow.blurb self.shareURL = currentShow.link LabelDescription.backgroundColor = UIColor.clearColor() slider.continuous = true } websiteURL = appDelegate.config.showURL subscribeURL = appDelegate.config.subscribeURL contactURL = appDelegate.config.contactURL notificationCenter.addObserverForName(kReachabilityChangedNotification, object: nil, queue: nil, usingBlock: { (notification) in var reach = notification.object as! Reachability if reach.isReachable() { self.playAudio() } else { self.appDelegate.alertForMissingConnection() } }) giveMyViewAGradient() setupAlertController() } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) self.navigationController?.setNavigationBarHidden(true, animated: false) self.navigationController?.navigationBar.tintColor = UIColor.whiteColor() } override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) if Timecode.text == nil { Timecode.text = "Loading..." } self.navigationController?.setNavigationBarHidden(false, animated: true) } override func viewWillDisappear(animated: Bool) { super.viewWillDisappear(animated) var myNavController = self.navigationController myNavController?.setNavigationBarHidden(true, animated: true) var browseViewController = myNavController?.topViewController as! BrowseViewController writeToBookmark(currentShow!) browseViewController.returnedFromPlayView() } override func viewWillTransitionToSize(size: CGSize, withTransitionCoordinator coordinator: UIViewControllerTransitionCoordinator) { view.setNeedsDisplay() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func didReceiveShow(show: Show, delegate radioplayer: Radio) { currentShow = show delegate = radioplayer if let currentShow = currentShow { delegate?.start(currentShow.audioLink!, sender:self) buttonState = playButtonStatus.Playing if currentShow.getBookmarkSeconds() != nil { restoreFromBookmark() } } } } extension PlayViewController { func playAudio() { delegate?.play() } func pausePressed() { delegate?.pauseAction() } func updateTime(timer: NSTimer) { let myDuration = delegate?.duration() if myDuration > 0 { slider?.maximumValue = myDuration! } if let mySeconds = delegate!.currentSeconds() { slider?.value = mySeconds if mySeconds > 0 { Timecode.text = delegate!.timecodes(mySeconds, duration:myDuration!).current Remaining.text = delegate!.timecodes(mySeconds, duration:myDuration!).remaining } } self.ActivityIndicator.hidden = true } func writeToBookmark(currentShow: Show) { if let currentSeconds = delegate?.currentSeconds() { currentShow.setBookmarkSeconds(currentSeconds) } if let totalSeconds = delegate?.duration() { // Use clock on AV Player to determine actual show duration currentShow.setTotalSeconds(totalSeconds) } } func restoreFromBookmark() { if let myBookmark = currentShow?.getBookmarkSeconds() { delegate!.setNewTime(myBookmark) } } @IBAction func didPressPause() { pausePressed() switch buttonState { case .Playing: buttonState = playButtonStatus.Paused pause.setImage(imagePlay, forState: UIControlState.Normal) case .Paused: buttonState = playButtonStatus.Playing pause.setImage(imagePause, forState: UIControlState.Normal) } } @IBAction func didPressMenu(sender: AnyObject) { self.presentViewController(alertController!, animated: true, completion: nil) } private func giveMyViewAGradient() { var gradient = CAGradientLayer() var bounds:CGRect = self.view.bounds gradient.frame = bounds let color1 = UIColor(red: 0.9, green: 0.9, blue: 0.9, alpha: 1.0).CGColor let color2 = UIColor(red: 0.85, green: 0.85, blue: 0.85, alpha: 1.0).CGColor let arrayColors = [color1, color2] gradient.colors = arrayColors view.layer.insertSublayer(gradient, atIndex: 0) } func setupAlertController() { alertController = UIAlertController(title: "The Peter B. Collins Show", message: nil, preferredStyle: UIAlertControllerStyle.ActionSheet) alertController!.view.tintColor = UIColor.orangeColor() var cancelAction = UIAlertAction(title: "Cancel", style:UIAlertActionStyle.Cancel, handler: nil) var shareAction = UIAlertAction(title: "Share", style:UIAlertActionStyle.Default, handler: {(alert: UIAlertAction!) in println("Share") self.shareTextImageAndURL(sharingText: self.LabelTitle.text, sharingImage: nil, sharingURL: self.shareURL) }) var goToWebsiteAction = UIAlertAction(title:"Go to Peter's website", style:UIAlertActionStyle.Default, handler: {(alert: UIAlertAction!) in UIApplication.sharedApplication().openURL(self.websiteURL!) return }) var subscribeAction = UIAlertAction(title:"Subscribe", style:UIAlertActionStyle.Default, handler: {(alert: UIAlertAction!) in UIApplication.sharedApplication().openURL(self.subscribeURL!) return }) var contactAction = UIAlertAction(title:"Contact", style:UIAlertActionStyle.Default, handler: {(alert: UIAlertAction!) in UIApplication.sharedApplication().openURL(self.contactURL!) return }) alertController?.addAction(cancelAction) alertController?.addAction(shareAction) alertController?.addAction(goToWebsiteAction) alertController?.addAction(subscribeAction) alertController?.addAction(contactAction) } private func shareTextImageAndURL(#sharingText: String?, sharingImage: UIImage?, sharingURL: NSURL?) { var sharingItems = [AnyObject]() if let text = sharingText { sharingItems.append(text) } if let image = sharingImage { sharingItems.append(image) } if let url = sharingURL { sharingItems.append(url) } let activityViewController = UIActivityViewController(activityItems: sharingItems, applicationActivities: nil) activityViewController.excludedActivityTypes = [ UIActivityTypeAddToReadingList, UIActivityTypeMessage ] self.presentViewController(activityViewController, animated: true, completion: nil) } func friendlyDate(myDate:NSDate?) -> String? { if myDate != nil { let dateFormatter = NSDateFormatter() dateFormatter.doesRelativeDateFormatting = true dateFormatter.timeStyle = .NoStyle dateFormatter.dateStyle = .LongStyle dateFormatter.timeZone = NSTimeZone.defaultTimeZone() dateFormatter.locale = NSLocale.currentLocale() var friendlyDateString:NSString = dateFormatter.stringFromDate(myDate!) return friendlyDateString as String } else { return nil } } }
mit
dduan/swift
validation-test/compiler_crashers_fixed/00012-emitdirecttypemetadataref.swift
6
622
// This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // RUN: %target-swift-frontend %s -emit-ir // Issue found by https://github.com/robrix (Rob Rix) // http://www.openradar.me/17822208 // https://twitter.com/rob_rix/status/493199478879682561 func a<T>() -> (T, T -> T) -> T { var b: ((T, T -> T) -> T)! return b }
apache-2.0
longitachi/ZLPhotoBrowser
Sources/General/ZLProgressView.swift
1
2377
// // ZLProgressView.swift // ZLPhotoBrowser // // Created by long on 2020/8/13. // // Copyright (c) 2020 Long Zhang <495181165@qq.com> // // 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 class ZLProgressView: UIView { private lazy var progressLayer: CAShapeLayer = { let layer = CAShapeLayer() layer.fillColor = UIColor.clear.cgColor layer.strokeColor = UIColor.white.cgColor layer.lineCap = .round layer.lineWidth = 4 return layer }() var progress: CGFloat = 0 { didSet { self.setNeedsDisplay() } } override init(frame: CGRect) { super.init(frame: frame) backgroundColor = .clear layer.addSublayer(progressLayer) } @available(*, unavailable) required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func draw(_ rect: CGRect) { let center = CGPoint(x: rect.width / 2, y: rect.height / 2) let radius = rect.width / 2 let end = -(.pi / 2) + (.pi * 2 * progress) progressLayer.frame = bounds let path = UIBezierPath(arcCenter: center, radius: radius, startAngle: -(.pi / 2), endAngle: end, clockwise: true) progressLayer.path = path.cgPath } }
mit
yannickl/FlowingMenu
Example/FlowingMenuTests/FlowingMenuTransitioningDelegateTests.swift
1
2026
// // FlowingMenuTransitioningDelegateTests.swift // FlowingMenuExample // // Created by Yannick LORIOT on 04/12/15. // Copyright © 2015 Yannick LORIOT. All rights reserved. // import XCTest class FlowingMenuTransitioningDelegateTests: XCTTestCaseTemplate { var transitionManager = FlowingMenuTransitionManager() override func setUp() { super.setUp() transitionManager = FlowingMenuTransitionManager() } func testAnimationControllerForPresentedController() { let presented = UIViewController() let presenting = UIViewController() let source = UIViewController() let animation = transitionManager.animationController(forPresented: presented, presenting: presenting, source: source) XCTAssertNotNil(animation) XCTAssertEqual(transitionManager.animationMode, FlowingMenuTransitionManager.AnimationMode.presentation) } func testAnimationControllerForDismissedController() { let dismissed = UIViewController() let animation = transitionManager.animationController(forDismissed: dismissed) XCTAssertNotNil(animation) XCTAssertEqual(transitionManager.animationMode, FlowingMenuTransitionManager.AnimationMode.dismissal) } func testInteractionControllerForPresentation() { XCTAssertFalse(transitionManager.interactive) var interaction = transitionManager.interactionControllerForPresentation(using: transitionManager) XCTAssertNil(interaction) transitionManager.interactive = true interaction = transitionManager.interactionControllerForPresentation(using: transitionManager) XCTAssertNotNil(interaction) } func testInteractionControllerForDismissal() { XCTAssertFalse(transitionManager.interactive) var interaction = transitionManager.interactionControllerForDismissal(using: transitionManager) XCTAssertNil(interaction) transitionManager.interactive = true interaction = transitionManager.interactionControllerForDismissal(using: transitionManager) XCTAssertNotNil(interaction) } }
mit
hwsyy/PlainReader
PlainReader/View/ArticleCellStarView.swift
5
954
// // ArticleCellStarView.swift // PlainReader // // Created by guo on 11/13/14. // Copyright (c) 2014 guojiubo. All rights reserved. // import UIKit class ArticleCellStarView: UIView { var star: UIImageView = UIImageView(image: UIImage(named: "ArticleUnstarred")) var starred: Bool = false { didSet { self.star.image = self.starred ? UIImage(named: "ArticleStarred") : UIImage(named: "ArticleUnstarred") } } override init(frame: CGRect) { super.init(frame: frame) self.setup() } required init(coder: NSCoder) { super.init(coder: coder) self.setup() } func setup() { self.star.center = CGPoint(x: CGRectGetWidth(self.bounds)/2, y: CGRectGetHeight(self.bounds)/2) self.star.autoresizingMask = .FlexibleLeftMargin | .FlexibleRightMargin | .FlexibleTopMargin | .FlexibleBottomMargin self.addSubview(self.star) } }
mit
clwm01/RTKitDemo
RCToolsDemo/RCToolsDemo/ErrorViewController.swift
2
1433
// // ErrorViewController.swift // RCToolsDemo // // Created by Rex Tsao on 5/12/16. // Copyright © 2016 rexcao. All rights reserved. // import UIKit class ErrorViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() self.view.backgroundColor = UIColor.whiteColor() self.attachComputeButton() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } private func attachComputeButton() { let comButton = UIButton() comButton.setTitle("compute", forState: .Normal) comButton.setTitleColor(UIColor.blackColor(), forState: .Normal) comButton.sizeToFit() comButton.setOrigin(CGPointMake(0, 64)) comButton.addTarget(self, action: #selector(ErrorViewController.compute), forControlEvents: .TouchUpInside) self.view.addSubview(comButton) } private func sum() throws -> Int { let a = 1 var b: Int? b = nil guard b != nil else { throw RTErrorType.Nil } return a + b! } func compute() { do { try self.sum() } catch RTErrorType.Nil { RTPrint.shareInstance().prt("nil error occurs") } catch { RTPrint.shareInstance().prt("other errors") } } }
mit
SummerHH/swift3.0WeBo
WeBo/Classes/View/PhotoBrowser/PhotoBrowserController.swift
1
6002
// // PhotoBrowserController.swift // WeBo // // Created by Apple on 16/11/20. // Copyright © 2016年 叶炯. All rights reserved. // import UIKit import SnapKit import SVProgressHUD private let PhotoBrowserCell = "PhotoBrowserCell" class PhotoBrowserController: UIViewController { // MARK:- 定义属性 var indexPath : IndexPath var picURLs : [URL] // MARK:- 懒加载属性 fileprivate lazy var collectionView : UICollectionView = UICollectionView(frame: CGRect.zero, collectionViewLayout: PhotoBrowserCollectionViewLayout()) fileprivate lazy var closeBtn : UIButton = UIButton(bgColor: UIColor.darkGray, fontSize: 14, title: "关 闭") fileprivate lazy var saveBtn : UIButton = UIButton(bgColor: UIColor.darkGray, fontSize: 14, title: "保 存") // MARK:- 自定义构造函数 init(indexPath : IndexPath, picURLs : [URL]) { self.indexPath = indexPath self.picURLs = picURLs super.init(nibName: nil, bundle: nil) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK:- 系统回调函数 override func loadView() { super.loadView() view.frame.size.width += 20 } override func viewDidLoad() { super.viewDidLoad() // 1.设置UI界面 setupUI() // 2.滚动到对应的图片 collectionView.selectItem(at: indexPath, animated: false, scrollPosition: .left) } } // MARK:- 设置UI界面内容 extension PhotoBrowserController { fileprivate func setupUI() { // 1.添加子控件 view.addSubview(collectionView) view.addSubview(closeBtn) view.addSubview(saveBtn) // 2.设置frame collectionView.frame = view.frame closeBtn.snp.makeConstraints { (make) -> Void in make.left.equalTo(20) make.bottom.equalTo(-20) make.size.equalTo(CGSize(width: 90, height: 32)) } saveBtn.snp.makeConstraints { (make) -> Void in make.right.equalTo(-20) make.bottom.equalTo(closeBtn.snp.bottom) make.size.equalTo(closeBtn.snp.size) } // 3.设置collectionView的属性 collectionView.register(PhotoBrowserViewCell.self, forCellWithReuseIdentifier: PhotoBrowserCell) collectionView.dataSource = self // 4.监听两个按钮的点击 closeBtn.addTarget(self, action: #selector(PhotoBrowserController.closeBtnClick), for: .touchUpInside) saveBtn.addTarget(self, action: #selector(PhotoBrowserController.saveBtnClick), for: .touchUpInside) } } // MARK:- 事件监听函数 extension PhotoBrowserController { @objc fileprivate func closeBtnClick() { dismiss(animated: true, completion: nil) } @objc fileprivate func saveBtnClick() { // 1.获取当前显示的图片 let cell = collectionView.visibleCells.first as! PhotoBrowserViewCell guard let image = cell.imageView.image else { return } // 2.将image对象保存相册 UIImageWriteToSavedPhotosAlbum(image, self, #selector(PhotoBrowserController.image(_:didFinishSavingWithError:contextInfo:)), nil) } @objc fileprivate func image(_ image : UIImage, didFinishSavingWithError error : NSError?, contextInfo : AnyObject) { var showInfo = "" if error != nil { showInfo = "保存失败" } else { showInfo = "保存成功" } SVProgressHUD.showInfo(withStatus: showInfo) } } // MARK:- 实现collectionView的数据源方法 extension PhotoBrowserController : UICollectionViewDataSource { func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return picURLs.count } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { // 1.创建cell let cell = collectionView.dequeueReusableCell(withReuseIdentifier: PhotoBrowserCell, for: indexPath) as! PhotoBrowserViewCell // 2.给cell设置数据 cell.picURL = picURLs[indexPath.item] cell.delegate = self return cell } } //MARK: - PhotoBrowserViewCellDelegate extension PhotoBrowserController: PhotoBrowserViewCellDelegate{ func imageViewBtnClick() { closeBtnClick() } } //MARK:- 遵守AnimatorDismissDelegate extension PhotoBrowserController: AnimatorDismissDelegate { func indexPathForDimissView() -> IndexPath { // 1.获取当前正在显示的indexPath let cell = collectionView.visibleCells.first! return collectionView.indexPath(for: cell)! } func imageViewForDimissView() -> UIImageView { // 1.创建UIImageView对象 let imageView = UIImageView() // 2.设置imageView的frame let cell = collectionView.visibleCells.first as! PhotoBrowserViewCell imageView.frame = cell.imageView.frame imageView.image = cell.imageView.image // 3.设置imageView的属性 imageView.contentMode = .scaleAspectFill imageView.clipsToBounds = true return imageView } } //MARK:- 自定义布局 class PhotoBrowserCollectionViewLayout : UICollectionViewFlowLayout { override func prepare() { super.prepare() // 1.设置itemSize itemSize = collectionView!.frame.size minimumInteritemSpacing = 0 minimumLineSpacing = 0 scrollDirection = .horizontal // 2.设置collectionView的属性 collectionView?.isPagingEnabled = true collectionView?.showsHorizontalScrollIndicator = false collectionView?.showsVerticalScrollIndicator = false } }
apache-2.0
weekwood/SwiftMime
Example/Tests/Tests.swift
1
576
// // SwiftMimeTests.swift // SwiftMimeTests // // Created by di wu on 2/9/15. // Copyright (c) 2015 di wu. All rights reserved. // import UIKit import XCTest import SwiftMime class SwiftMimeTests: XCTestCase { override func setUp() { super.setUp() } override func tearDown() { super.tearDown() } func testLookupType() { XCTAssertEqual(SwiftMime.mime("txt"), "text/plain", "pass") } func testLookupExtension() { XCTAssertEqual(SwiftMime.ext("application/atom+xml"), "atom", "pass") } }
mit
apple/swift-lldb
packages/Python/lldbsuite/test/lang/swift/variables/bulky_enums/main.swift
2
1116
// main.swift // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // // ----------------------------------------------------------------------------- struct S { var a = 1 var b = 2 } struct Q { var a = S() var b = S() init(a: Int, b: Int) { self.a = S(a: a, b: b) self.b = S(a: a, b: b) } } enum E { case A(Q,Q?) case B(Q,[Q]?) case C(Q,[Q]?) case D(Q,Q) case E(Q,Q) case F(Q,[Q]?) case G(Q,Q) case H(Q,Q) case I(Q,[Q]?) case J(Q,Q) case K(Q,Q) case L(Q,Q) case M(Q,Q) case N(Q,Q) case O(Q,Q) case P(Q,Q) case R(Q,Q) case T(Q,Q) case U(Q,Q) case V(Q,Q) case W(String,Q,Q?) case X(String,Q,Q) case Y(Q,Q?) case Z(Q,Q?) } func main() { var e: E? = E.X("hello world", Q(a: 100, b: 200), Q(a: 300, b: 400)) print(e) // break here } main()
apache-2.0
omise/omise-ios
OmiseSDK/Compatibility/OmiseCapability.swift
1
9665
// swiftlint:disable type_name import Foundation @objc(OMSCapability) public class __OmiseCapability: NSObject { let capability: Capability @objc public lazy var location: String = capability.location @objc public lazy var object: String = capability.object @objc public lazy var supportedBanks: Set<String> = capability.supportedBanks @objc public lazy var supportedBackends: [__OmiseCapabilityBackend] = capability.supportedBackends.map(__OmiseCapabilityBackend.init) init(capability: Capability) { self.capability = capability } } @objc(OMSCapabilityBackend) public class __OmiseCapabilityBackend: NSObject { private let backend: Capability.Backend @objc public lazy var payment: __OmiseCapabilityBackendPayment = __OmiseCapabilityBackendPayment.makeCapabilityBackend(from: backend.payment) @objc public lazy var supportedCurrencyCodes: Set<String> = Set(backend.supportedCurrencies.map { $0.code }) required init(_ backend: Capability.Backend) { self.backend = backend } } @objc(OMSCapabilityBackendPayment) public class __OmiseCapabilityBackendPayment: NSObject {} @objc(OMSCapabilityCardBackend) public class __OmiseCapabilityCardBackendPayment: __OmiseCapabilityBackendPayment { @objc public let supportedBrands: Set<String> init(supportedBrands: Set<String>) { self.supportedBrands = supportedBrands } } @objc(OMSCapabilitySourceBackend) public class __OmiseCapabilitySourceBackendPayment: __OmiseCapabilityBackendPayment { @objc public let type: OMSSourceTypeValue init(sourceType: OMSSourceTypeValue) { self.type = sourceType } static let alipaySourceBackendPayment = __OmiseCapabilitySourceBackendPayment(sourceType: OMSSourceTypeValue.alipay) static let alipayCNSourceBackendPayment = __OmiseCapabilitySourceBackendPayment(sourceType: OMSSourceTypeValue.alipayCN) static let alipayHKSourceBackendPayment = __OmiseCapabilitySourceBackendPayment(sourceType: OMSSourceTypeValue.alipayHK) static let danaSourceBackendPayment = __OmiseCapabilitySourceBackendPayment(sourceType: OMSSourceTypeValue.dana) static let gcashSourceBackendPayment = __OmiseCapabilitySourceBackendPayment(sourceType: OMSSourceTypeValue.gcash) static let kakaoPaySourceBackendPayment = __OmiseCapabilitySourceBackendPayment(sourceType: OMSSourceTypeValue.kakaoPay) static let touchNGoSourceBackendPayment = __OmiseCapabilitySourceBackendPayment(sourceType: OMSSourceTypeValue.touchNGo) static let promptpaySourceBackendPayment = __OmiseCapabilitySourceBackendPayment(sourceType: OMSSourceTypeValue.promptPay) static let paynowSourceBackendPayment = __OmiseCapabilitySourceBackendPayment(sourceType: OMSSourceTypeValue.payNow) static let truemoneySourceBackendPayment = __OmiseCapabilitySourceBackendPayment(sourceType: OMSSourceTypeValue.trueMoney) static let cityPointsSourceBackendPayment = __OmiseCapabilitySourceBackendPayment(sourceType: OMSSourceTypeValue.pointsCiti) static let eContextSourceBackendPayment = __OmiseCapabilitySourceBackendPayment(sourceType: OMSSourceTypeValue.eContext) static let FPXSourceBackendPayment = __OmiseCapabilitySourceBackendPayment(sourceType: OMSSourceTypeValue.fpx) static let rabbitLinepaySourceBackendPayment = __OmiseCapabilitySourceBackendPayment(sourceType: OMSSourceTypeValue.rabbitLinepay) static let ocbcPaoSourceBackendPayment = __OmiseCapabilitySourceBackendPayment(sourceType: OMSSourceTypeValue.mobileBankingOCBCPAO) static let grabPaySourceBackendPayment = __OmiseCapabilitySourceBackendPayment(sourceType: OMSSourceTypeValue.grabPay) static let boostSourceBackendPayment = __OmiseCapabilitySourceBackendPayment(sourceType: OMSSourceTypeValue.boost) static let shopeePaySourceBackendPayment = __OmiseCapabilitySourceBackendPayment(sourceType: OMSSourceTypeValue.shopeePay) static let shopeePayJumpAppSourceBackendPayment = __OmiseCapabilitySourceBackendPayment(sourceType: OMSSourceTypeValue.shopeePayJumpApp) static let maybankQRPaySourceBackendPayment = __OmiseCapabilitySourceBackendPayment(sourceType: OMSSourceTypeValue.maybankQRPay) static let duitNowQRSourceBackendPayment = __OmiseCapabilitySourceBackendPayment(sourceType: OMSSourceTypeValue.duitNowQR) static let duitNowOBWSourceBackendPayment = __OmiseCapabilitySourceBackendPayment(sourceType: OMSSourceTypeValue.duitNowOBW) static func makeInternetBankingSourceBackendPayment( bank: PaymentInformation.InternetBanking ) -> __OmiseCapabilitySourceBackendPayment { return __OmiseCapabilitySourceBackendPayment(sourceType: OMSSourceTypeValue(bank.type)) } static func makeMobileBankingSourceBackendPayment( bank: PaymentInformation.MobileBanking ) -> __OmiseCapabilitySourceBackendPayment { return __OmiseCapabilitySourceBackendPayment(sourceType: OMSSourceTypeValue(bank.type)) } } @objc(OMSCapabilityInstallmentBackend) public class __OmiseCapabilityInstallmentBackendPayment: __OmiseCapabilitySourceBackendPayment { @objc public let availableNumberOfTerms: IndexSet init(sourceType: OMSSourceTypeValue, availableNumberOfTerms: IndexSet) { self.availableNumberOfTerms = availableNumberOfTerms super.init(sourceType: sourceType) } } @objc(OMSCapabilityUnknownSourceBackend) public class __OmiseCapabilityUnknownSourceBackendPayment: __OmiseCapabilitySourceBackendPayment { @objc public let parameters: [String: Any] init(sourceType: String, parameters: [String: Any]) { self.parameters = parameters super.init(sourceType: OMSSourceTypeValue(rawValue: sourceType)) } } extension __OmiseCapabilityBackendPayment { // swiftlint:disable function_body_length static func makeCapabilityBackend(from payment: Capability.Backend.Payment) -> __OmiseCapabilityBackendPayment { switch payment { case .card(let brands): return __OmiseCapabilityCardBackendPayment(supportedBrands: Set(brands.map({ $0.description }))) case .installment(let brand, availableNumberOfTerms: let availableNumberOfTerms): return __OmiseCapabilityInstallmentBackendPayment( sourceType: OMSSourceTypeValue(brand.type), availableNumberOfTerms: availableNumberOfTerms ) case .internetBanking(let bank): return __OmiseCapabilitySourceBackendPayment.makeInternetBankingSourceBackendPayment(bank: bank) case .mobileBanking(let bank): return __OmiseCapabilitySourceBackendPayment.makeMobileBankingSourceBackendPayment(bank: bank) case .billPayment(let billPayment): return __OmiseCapabilitySourceBackendPayment(sourceType: OMSSourceTypeValue(billPayment.type)) case .alipay: return __OmiseCapabilitySourceBackendPayment.alipaySourceBackendPayment case .alipayCN: return __OmiseCapabilitySourceBackendPayment.alipayCNSourceBackendPayment case .alipayHK: return __OmiseCapabilitySourceBackendPayment.alipayHKSourceBackendPayment case .dana: return __OmiseCapabilitySourceBackendPayment.danaSourceBackendPayment case .gcash: return __OmiseCapabilitySourceBackendPayment.gcashSourceBackendPayment case .kakaoPay: return __OmiseCapabilitySourceBackendPayment.kakaoPaySourceBackendPayment case .touchNGoAlipayPlus, .touchNGo: return __OmiseCapabilitySourceBackendPayment.touchNGoSourceBackendPayment case .promptpay: return __OmiseCapabilitySourceBackendPayment.promptpaySourceBackendPayment case .paynow: return __OmiseCapabilitySourceBackendPayment.paynowSourceBackendPayment case .truemoney: return __OmiseCapabilitySourceBackendPayment.truemoneySourceBackendPayment case .points(let points): return __OmiseCapabilitySourceBackendPayment(sourceType: OMSSourceTypeValue(points.type)) case .eContext: return __OmiseCapabilitySourceBackendPayment.eContextSourceBackendPayment case .fpx: return __OmiseCapabilitySourceBackendPayment.FPXSourceBackendPayment case .rabbitLinepay: return __OmiseCapabilitySourceBackendPayment.rabbitLinepaySourceBackendPayment case .ocbcPao: return __OmiseCapabilitySourceBackendPayment.ocbcPaoSourceBackendPayment case .grabPay, .grabPayRms: return __OmiseCapabilitySourceBackendPayment.grabPaySourceBackendPayment case .boost: return __OmiseCapabilitySourceBackendPayment.boostSourceBackendPayment case .shopeePay: return __OmiseCapabilitySourceBackendPayment.shopeePaySourceBackendPayment case .shopeePayJumpApp: return __OmiseCapabilitySourceBackendPayment.shopeePayJumpAppSourceBackendPayment case .maybankQRPay: return __OmiseCapabilitySourceBackendPayment.maybankQRPaySourceBackendPayment case .duitNowQR: return __OmiseCapabilitySourceBackendPayment.duitNowQRSourceBackendPayment case .duitNowOBW: return __OmiseCapabilitySourceBackendPayment.duitNowOBWSourceBackendPayment case .unknownSource(let type, let configurations): return __OmiseCapabilityUnknownSourceBackendPayment(sourceType: type, parameters: configurations) } } }
mit
gregomni/swift
test/Constraints/tuple.swift
2
11204
// RUN: %target-typecheck-verify-swift // Test various tuple constraints. func f0(x: Int, y: Float) {} var i : Int var j : Int var f : Float func f1(y: Float, rest: Int...) {} func f2(_: (_ x: Int, _ y: Int) -> Int) {} func f2xy(x: Int, y: Int) -> Int {} func f2ab(a: Int, b: Int) -> Int {} func f2yx(y: Int, x: Int) -> Int {} func f3(_ x: (_ x: Int, _ y: Int) -> ()) {} func f3a(_ x: Int, y: Int) {} func f3b(_: Int) {} func f4(_ rest: Int...) {} func f5(_ x: (Int, Int)) {} func f6(_: (i: Int, j: Int), k: Int = 15) {} //===----------------------------------------------------------------------===// // Conversions and shuffles //===----------------------------------------------------------------------===// func foo(a : [(some: Int, (key: Int, value: String))]) -> String { for (i , (j, k)) in a { if i == j { return k } } } func rdar28207648() -> [(Int, CustomStringConvertible)] { let v : [(Int, Int)] = [] return v as [(Int, CustomStringConvertible)] } class rdar28207648Base {} class rdar28207648Derived : rdar28207648Base {} func rdar28207648(x: (Int, rdar28207648Derived)) -> (Int, rdar28207648Base) { return x as (Int, rdar28207648Base) } public typealias Success<T, V> = (response: T, data: V?) public enum Result { case success(Success<Any, Any>) case error(Error) } let a = Success<Int, Int>(response: 3, data: 3) let success: Result = .success(a) // Variadic functions. f4() f4(1) f4(1, 2, 3) f2(f2xy) f2(f2ab) f2(f2yx) f3(f3a) f3(f3b) // expected-error{{cannot convert value of type '(Int) -> ()' to expected argument type '(Int, Int) -> ()'}} func getIntFloat() -> (int: Int, float: Float) {} var values = getIntFloat() func wantFloat(_: Float) {} wantFloat(values.float) var e : (x: Int..., y: Int) // expected-error{{cannot create a variadic tuple}} typealias Interval = (a:Int, b:Int) func takeInterval(_ x: Interval) {} takeInterval(Interval(1, 2)) f5((1,1)) // Tuples with existentials var any : Any = () any = (1, 2) any = (label: 4) // expected-error {{cannot create a single-element tuple with an element label}} // Scalars don't have .0/.1/etc i = j.0 // expected-error{{value of type 'Int' has no member '0'}} any.1 // expected-error{{value of type 'Any' has no member '1'}} // expected-note@-1{{cast 'Any' to 'AnyObject' or use 'as!' to force downcast to a more specific type to access members}} any = (5.0, 6.0) as (Float, Float) _ = (any as! (Float, Float)).1 // Fun with tuples protocol PosixErrorReturn { static func errorReturnValue() -> Self } extension Int : PosixErrorReturn { static func errorReturnValue() -> Int { return -1 } } func posixCantFail<A, T : Comparable & PosixErrorReturn> (_ f: @escaping (A) -> T) -> (_ args:A) -> T { return { args in let result = f(args) assert(result != T.errorReturnValue()) return result } } func open(_ name: String, oflag: Int) -> Int { } var foo: Int = 0 var fd = posixCantFail(open)(("foo", 0)) // Tuples and lvalues class C { init() {} func f(_: C) {} } func testLValue(_ c: C) { var c = c c.f(c) let x = c c = x } // <rdar://problem/21444509> Crash in TypeChecker::coercePatternToType func invalidPatternCrash(_ k : Int) { switch k { case (k, cph_: k) as UInt8: // expected-error {{tuple pattern cannot match values of the non-tuple type 'UInt8'}} expected-warning {{cast from 'Int' to unrelated type 'UInt8' always fails}} break } } // <rdar://problem/21875219> Tuple to tuple conversion with IdentityExpr / AnyTryExpr hang class Paws { init() throws {} } func scruff() -> (AnyObject?, Error?) { do { return try (Paws(), nil) } catch { return (nil, error) } } // Test variadics with trailing closures. func variadicWithTrailingClosure(_ x: Int..., y: Int = 2, fn: (Int, Int) -> Int) { } variadicWithTrailingClosure(1, 2, 3) { $0 + $1 } variadicWithTrailingClosure(1) { $0 + $1 } variadicWithTrailingClosure() { $0 + $1 } variadicWithTrailingClosure { $0 + $1 } variadicWithTrailingClosure(1, 2, 3, y: 0) { $0 + $1 } variadicWithTrailingClosure(1, y: 0) { $0 + $1 } variadicWithTrailingClosure(y: 0) { $0 + $1 } variadicWithTrailingClosure(1, 2, 3, y: 0, fn: +) variadicWithTrailingClosure(1, y: 0, fn: +) variadicWithTrailingClosure(y: 0, fn: +) variadicWithTrailingClosure(1, 2, 3, fn: +) variadicWithTrailingClosure(1, fn: +) variadicWithTrailingClosure(fn: +) // <rdar://problem/23700031> QoI: Terrible diagnostic in tuple assignment func gcd_23700031<T>(_ a: T, b: T) { var a = a var b = b (a, b) = (b, a % b) // expected-error {{binary operator '%' cannot be applied to two 'T' operands}} } // <rdar://problem/24210190> // Don't ignore tuple labels in same-type constraints or stronger. protocol Kingdom { associatedtype King } struct Victory<General> { init<K: Kingdom>(_ king: K) where K.King == General {} // expected-note {{where 'General' = '(x: Int, y: Int)', 'K.King' = 'MagicKingdom<(Int, Int)>.King' (aka '(Int, Int)')}} } struct MagicKingdom<K> : Kingdom { typealias King = K } func magify<T>(_ t: T) -> MagicKingdom<T> { return MagicKingdom() } func foo(_ pair: (Int, Int)) -> Victory<(x: Int, y: Int)> { return Victory(magify(pair)) // expected-error {{initializer 'init(_:)' requires the types '(x: Int, y: Int)' and 'MagicKingdom<(Int, Int)>.King' (aka '(Int, Int)') be equivalent}} } // https://bugs.swift.org/browse/SR-596 // Compiler crashes when accessing a non-existent property of a closure parameter func call(_ f: (C) -> Void) {} func makeRequest() { call { obj in print(obj.invalidProperty) // expected-error {{value of type 'C' has no member 'invalidProperty'}} } } // <rdar://problem/25271859> QoI: Misleading error message when expression result can't be inferred from closure struct r25271859<T> { } extension r25271859 { func map<U>(f: (T) -> U) -> r25271859<U> { } func andThen<U>(f: (T) -> r25271859<U>) { } } func f(a : r25271859<(Float, Int)>) { a.map { $0.0 } .andThen { _ in print("hello") return r25271859<String>() } } // LValue to rvalue conversions. func takesRValue(_: (Int, (Int, Int))) {} func takesAny(_: Any) {} var x = 0 var y = 0 let _ = (x, (y, 0)) takesRValue((x, (y, 0))) takesAny((x, (y, 0))) // SR-2600 - Closure cannot infer tuple parameter names typealias Closure<A, B> = ((a: A, b: B)) -> String func invoke<A, B>(a: A, b: B, _ closure: Closure<A,B>) { print(closure((a, b))) } invoke(a: 1, b: "B") { $0.b } invoke(a: 1, b: "B") { $0.1 } invoke(a: 1, b: "B") { (c: (a: Int, b: String)) in return c.b } invoke(a: 1, b: "B") { c in return c.b } // Crash with one-element tuple with labeled element class Dinner {} func microwave() -> Dinner? { let d: Dinner? = nil return (n: d) // expected-error{{cannot convert return expression of type '(n: Dinner?)' to return type 'Dinner?'}} } func microwave() -> Dinner { let d: Dinner? = nil return (n: d) // expected-error{{cannot convert return expression of type '(n: Dinner?)' to return type 'Dinner'}} } // Tuple conversion with an optional func f(b: Bool) -> (a: Int, b: String)? { let x = 3 let y = "" return b ? (x, y) : nil } // Single element tuple expressions func singleElementTuple() { let _ = (label: 123) // expected-error {{cannot create a single-element tuple with an element label}} {{12-19=}} let _ = (label: 123).label // expected-error {{cannot create a single-element tuple with an element label}} {{12-19=}} let _ = ((label: 123)) // expected-error {{cannot create a single-element tuple with an element label}} {{13-20=}} let _ = ((label: 123)).label // expected-error {{cannot create a single-element tuple with an element label}} {{13-20=}} } // Tuples with duplicate labels let dupLabel1: (foo: Int, foo: Int) = (foo: 1, foo: 2) // expected-error 2{{cannot create a tuple with a duplicate element label}} func dupLabel2(x a: Int, x b: Int) -> (y: Int, y: Int) { // expected-error {{cannot create a tuple with a duplicate element label}} return (a, b) } let _ = (bar: 0, bar: "") // expected-error {{cannot create a tuple with a duplicate element label}} let zeroTuple = (0,0) if case (foo: let x, foo: let y) = zeroTuple { print(x+y) } // expected-error {{cannot create a tuple with a duplicate element label}} // expected-warning@-1 {{'if' condition is always true}} enum BishBash { case bar(foo: Int, foo: String) } // expected-error@-1 {{invalid redeclaration of 'foo'}} // expected-note@-2 {{'foo' previously declared here}} let enumLabelDup: BishBash = .bar(foo: 0, foo: "") // expected-error {{cannot create a tuple with a duplicate element label}} func dupLabelClosure(_ fn: () -> Void) {} dupLabelClosure { print((bar: "", bar: 5).bar) } // expected-error {{cannot create a tuple with a duplicate element label}} struct DupLabelSubscript { subscript(foo x: Int, foo y: Int) -> Int { return 0 } } let dupLabelSubscriptStruct = DupLabelSubscript() let _ = dupLabelSubscriptStruct[foo: 5, foo: 5] // ok // SR-12869 var dict: [String: (Int, Int)] = [:] let bignum: Int64 = 1337 dict["test"] = (bignum, 1) // expected-error {{cannot assign value of type '(Int64, Int)' to subscript of type '(Int, Int)'}} var tuple: (Int, Int) tuple = (bignum, 1) // expected-error {{cannot assign value of type '(Int64, Int)' to type '(Int, Int)'}} var optionalTuple: (Int, Int)? var optionalTuple2: (Int64, Int)? = (bignum, 1) var optionalTuple3: (UInt64, Int)? = (bignum, 1) // expected-error {{cannot convert value of type '(Int64, Int)' to specified type '(UInt64, Int)?'}} optionalTuple = (bignum, 1) // expected-error {{cannot assign value of type '(Int64, Int)' to type '(Int, Int)'}} // Optional to Optional optionalTuple = optionalTuple2 // expected-error {{cannot assign value of type '(Int64, Int)?' to type '(Int, Int)?'}} func testTupleLabelMismatchFuncConversion(fn1: @escaping ((x: Int, y: Int)) -> Void, fn2: @escaping () -> (x: Int, Int)) { // Warn on mismatches let _: ((a: Int, b: Int)) -> Void = fn1 // expected-warning {{tuple conversion from '(a: Int, b: Int)' to '(x: Int, y: Int)' mismatches labels}} let _: ((x: Int, b: Int)) -> Void = fn1 // expected-warning {{tuple conversion from '(x: Int, b: Int)' to '(x: Int, y: Int)' mismatches labels}} let _: () -> (y: Int, Int) = fn2 // expected-warning {{tuple conversion from '(x: Int, Int)' to '(y: Int, Int)' mismatches labels}} let _: () -> (y: Int, k: Int) = fn2 // expected-warning {{tuple conversion from '(x: Int, Int)' to '(y: Int, k: Int)' mismatches labels}} // Attempting to shuffle has always been illegal here let _: () -> (y: Int, x: Int) = fn2 // expected-error {{cannot convert value of type '() -> (x: Int, Int)' to specified type '() -> (y: Int, x: Int)'}} // Losing labels is okay though. let _: () -> (Int, Int) = fn2 // Gaining labels also okay. let _: ((x: Int, Int)) -> Void = fn1 let _: () -> (x: Int, y: Int) = fn2 let _: () -> (Int, y: Int) = fn2 } func testTupleLabelMismatchKeyPath() { // Very Cursed. let _: KeyPath<(x: Int, y: Int), Int> = \(a: Int, b: Int).x // expected-warning@-1 {{tuple conversion from '(a: Int, b: Int)' to '(x: Int, y: Int)' mismatches labels}} }
apache-2.0
gregomni/swift
test/decl/protocol/req/recursion.swift
2
3834
// RUN: %target-typecheck-verify-swift -requirement-machine-inferred-signatures=on protocol SomeProtocol { associatedtype T } extension SomeProtocol where T == Optional<T> { } // expected-error@-1 {{cannot build rewrite system for generic signature; concrete nesting limit exceeded}} // expected-note@-2 {{failed rewrite rule is τ_0_0.[SomeProtocol:T].[concrete: Optional<Optional<Optional<Optional<Optional<Optional<Optional<Optional<Optional<Optional<Optional<Optional<Optional<Optional<Optional<Optional<Optional<Optional<Optional<Optional<Optional<Optional<Optional<Optional<Optional<Optional<Optional<Optional<Optional<Optional<τ_0_0.[SomeProtocol:T]>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>] => τ_0_0.[SomeProtocol:T]}} // rdar://problem/19840527 class X<T> where T == X { // expected-error@-1 {{cannot build rewrite system for generic signature; concrete nesting limit exceeded}} // expected-note@-2 {{failed rewrite rule is τ_0_0.[concrete: X<X<X<X<X<X<X<X<X<X<X<X<X<X<X<X<X<X<X<X<X<X<X<X<X<X<X<X<X<X<τ_0_0>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>] => τ_0_0}} // expected-error@-3 3{{generic class 'X' has self-referential generic requirements}} var type: T { return Swift.type(of: self) } // expected-error{{cannot convert return expression of type 'X<T>.Type' to return type 'T'}} } // FIXME: The "associated type 'Foo' is not a member type of 'Self'" diagnostic // should also become "associated type 'Foo' references itself" protocol CircularAssocTypeDefault { associatedtype Z = Z // expected-error{{associated type 'Z' references itself}} // expected-note@-1{{type declared here}} // expected-note@-2{{protocol requires nested type 'Z'; do you want to add it?}} associatedtype Z2 = Z3 // expected-note@-1{{protocol requires nested type 'Z2'; do you want to add it?}} associatedtype Z3 = Z2 // expected-note@-1{{protocol requires nested type 'Z3'; do you want to add it?}} associatedtype Z4 = Self.Z4 // expected-error{{associated type 'Z4' references itself}} // expected-note@-1{{type declared here}} // expected-note@-2{{protocol requires nested type 'Z4'; do you want to add it?}} associatedtype Z5 = Self.Z6 // expected-note@-1{{protocol requires nested type 'Z5'; do you want to add it?}} associatedtype Z6 = Self.Z5 // expected-note@-1{{protocol requires nested type 'Z6'; do you want to add it?}} } struct ConformsToCircularAssocTypeDefault : CircularAssocTypeDefault { } // expected-error@-1 {{type 'ConformsToCircularAssocTypeDefault' does not conform to protocol 'CircularAssocTypeDefault'}} // rdar://problem/20000145 public protocol P { associatedtype T } public struct S<A: P> where A.T == S<A> { // expected-error@-1 3{{generic struct 'S' has self-referential generic requirements}} func f(a: A.T) { g(a: id(t: a)) // `a` has error type which is diagnosed as circular reference _ = A.T.self } func g(a: S<A>) { f(a: id(t: a)) _ = S<A>.self } func id<T>(t: T) -> T { return t } } protocol I { init() } protocol PI { associatedtype T : I } struct SI<A: PI> : I where A : I, A.T == SI<A> { // expected-error@-1 3{{generic struct 'SI' has self-referential generic requirements}} func ggg<T : I>(t: T.Type) -> T { return T() } func foo() { _ = A() _ = A.T() _ = SI<A>() _ = ggg(t: A.self) _ = ggg(t: A.T.self) _ = self.ggg(t: A.self) _ = self.ggg(t: A.T.self) } } // Used to hit infinite recursion struct S4<A: PI> : I where A : I { } struct S5<A: PI> : I where A : I, A.T == S4<A> { } // Used to hit ArchetypeBuilder assertions struct SU<A: P> where A.T == SU { // expected-error@-1 3{{generic struct 'SU' has self-referential generic requirements}} } struct SIU<A: PI> : I where A : I, A.T == SIU { // expected-error@-1 3{{generic struct 'SIU' has self-referential generic requirements}} }
apache-2.0
banjun/SwiftBeaker
Examples/06. Requests.swift
1
5617
import Foundation import APIKit import URITemplate protocol URITemplateContextConvertible: Encodable {} extension URITemplateContextConvertible { var context: [String: String] { return ((try? JSONSerialization.jsonObject(with: JSONEncoder().encode(self))) as? [String: String]) ?? [:] } } public enum RequestError: Error { case encode } public enum ResponseError: Error { case undefined(Int, String?) case invalidData(Int, String?) } struct RawDataParser: DataParser { var contentType: String? {return nil} func parse(data: Data) -> Any { return data } } struct TextBodyParameters: BodyParameters { let contentType: String let content: String func buildEntity() throws -> RequestBodyEntity { guard let r = content.data(using: .utf8) else { throw RequestError.encode } return .data(r) } } public protocol APIBlueprintRequest: Request {} extension APIBlueprintRequest { public var dataParser: DataParser {return RawDataParser()} func contentMIMEType(in urlResponse: HTTPURLResponse) -> String? { return (urlResponse.allHeaderFields["Content-Type"] as? String)?.components(separatedBy: ";").first?.trimmingCharacters(in: .whitespaces) } func data(from object: Any, urlResponse: HTTPURLResponse) throws -> Data { guard let d = object as? Data else { throw ResponseError.invalidData(urlResponse.statusCode, contentMIMEType(in: urlResponse)) } return d } func string(from object: Any, urlResponse: HTTPURLResponse) throws -> String { guard let s = String(data: try data(from: object, urlResponse: urlResponse), encoding: .utf8) else { throw ResponseError.invalidData(urlResponse.statusCode, contentMIMEType(in: urlResponse)) } return s } func decodeJSON<T: Decodable>(from object: Any, urlResponse: HTTPURLResponse) throws -> T { return try JSONDecoder().decode(T.self, from: data(from: object, urlResponse: urlResponse)) } public func intercept(object: Any, urlResponse: HTTPURLResponse) throws -> Any { return object } } protocol URITemplateRequest: Request { static var pathTemplate: URITemplate { get } associatedtype PathVars: URITemplateContextConvertible var pathVars: PathVars { get } } extension URITemplateRequest { // reconstruct URL to use URITemplate.expand. NOTE: APIKit does not support URITemplate format other than `path + query` public func intercept(urlRequest: URLRequest) throws -> URLRequest { var req = urlRequest req.url = URL(string: baseURL.absoluteString + type(of: self).pathTemplate.expand(pathVars.context))! return req } } /// indirect Codable Box-like container for recursive data structure definitions public class Indirect<V: Codable>: Codable { public var value: V public init(_ value: V) { self.value = value } public required init(from decoder: Decoder) throws { self.value = try V(from: decoder) } public func encode(to encoder: Encoder) throws { try value.encode(to: encoder) } } // MARK: - Transitions /// In API Blueprint, _requests_ can hold exactly the same kind of information and /// can be described using exactly the same structure as _responses_, only with /// different signature – using the `Request` keyword. The string that follows /// after the `Request` keyword is a request identifier. Again, using explanatory /// and simple naming is the best way to go. struct Retrieve_a_Message: APIBlueprintRequest { let baseURL: URL var method: HTTPMethod {return .get} var path: String {return "/message"} enum Responses { case http200_text_plain(String) case http200_application_json(Void) } var headerFields: [String: String] {return headerVars.context} var headerVars: HeaderVars struct HeaderVars: URITemplateContextConvertible { /// text/plain var accept: String enum CodingKeys: String, CodingKey { case accept = "Accept" } } func response(from object: Any, urlResponse: HTTPURLResponse) throws -> Responses { let contentType = contentMIMEType(in: urlResponse) switch (urlResponse.statusCode, contentType) { case (200, "text/plain"?): return .http200_text_plain(try string(from: object, urlResponse: urlResponse)) case (200, "application/json"?): return .http200_application_json(try decodeJSON(from: object, urlResponse: urlResponse)) default: throw ResponseError.undefined(urlResponse.statusCode, contentType) } } } struct Update_a_Message: APIBlueprintRequest { let baseURL: URL var method: HTTPMethod {return .put} var path: String {return "/message"} let param: String var bodyParameters: BodyParameters? {return TextBodyParameters(contentType: "text/plain", content: param)} enum Responses { case http204_(Void) case http204_(Void) } func response(from object: Any, urlResponse: HTTPURLResponse) throws -> Responses { let contentType = contentMIMEType(in: urlResponse) switch (urlResponse.statusCode, contentType) { case (204, _): return .http204_(try decodeJSON(from: object, urlResponse: urlResponse)) case (204, _): return .http204_(try decodeJSON(from: object, urlResponse: urlResponse)) default: throw ResponseError.undefined(urlResponse.statusCode, contentType) } } } // MARK: - Data Structures
mit
Liquidsoul/Sourcery-AutoJSONSerializable
Sources/AutoJSONSerialization/Models/IntEnumProperty.swift
1
233
enum IntEnum: Int { case zero = 0 case one case two case four = 4 } // sourcery: AutoJSONDeserializable, AutoJSONSerializable struct IntEnumProperty { let enumValue: IntEnum let optionalEnumValue: IntEnum? }
mit
exponent/exponent
ios/vendored/unversioned/@stripe/stripe-react-native/ios/StripeContainerManager.swift
2
274
import Foundation @objc(StripeContainerManager) class StripeContainerManager: RCTViewManager { override func view() -> UIView! { return StripeContainerView() } override class func requiresMainQueueSetup() -> Bool { return false } }
bsd-3-clause
fcanas/Formulary
Exemplary/ViewController.swift
1
2756
// // ViewController.swift // Exemplary // // Created by Fabian Canas on 1/16/15. // Copyright (c) 2015 Fabian Canas. All rights reserved. // import UIKit import Formulary class ViewController: FormViewController { override func viewDidLoad() { super.viewDidLoad() navigationItem.rightBarButtonItem = editButtonItem let decimalFormatter = NumberFormatter() decimalFormatter.maximumFractionDigits = 5 let integerFormatter = NumberFormatter() self.form = Form(sections: [ FormSection(rows: [ TextEntryFormRow(name:"Name", tag: "name", validation: RequiredString("Name")), TextEntryFormRow(name: "Email", tag: "email", textType: TextEntryType.email), TextEntryFormRow(name:"Age", tag: "age", textType: TextEntryType.number, validation: MinimumNumber("Age", 13), formatter: integerFormatter)], name:"Profile"), FormSection(rows: [ TextEntryFormRow(name:"Favorite Number", tag: "favoriteNumber", textType: .decimal, value: nil, validation: MinimumNumber("Your favorite number", 47) && MaximumNumber("Your favorite number", 47), formatter: decimalFormatter), FormRow(name:"Do you like goats?", tag: "likesGoats", type: .toggleSwitch, value: false as AnyObject?), TextEntryFormRow(name:"Other Thoughts?", tag: "thoughts", textType: .plain),], name:"Preferences", footerName: "Fin"), OptionSection(rowValues:["Ice Cream", "Pizza", "Beer"], name: "Food", value: ["Pizza", "Ice Cream"]), FormSection(rows: [PickerFormRow(name: "House", options: ["Gryffindor", "Ravenclaw", "Slytherin", "Hufflepuff"])], name: "House"), FormSection(rows: [ FormRow(name:"Show Values", tag: "show", type: .button, value: nil, action: { _ in let data = try! JSONSerialization.data(withJSONObject: values(self.form), options: []) let s = NSString(data: data, encoding: String.Encoding.utf8.rawValue) let alert = UIAlertController(title: "Form Values", message: s as String?, preferredStyle: UIAlertControllerStyle.alert) alert.addAction(UIAlertAction(title: "Ok", style: UIAlertActionStyle.default, handler: nil)) self.present(alert, animated: true, completion: nil) }) ]), ]) setEditing(true, animated: false) } override func setEditing(_ editing: Bool, animated: Bool) { super.setEditing(editing, animated: animated) editingEnabled = editing } }
mit
EasySwift/EasySwift
Carthage/Checkouts/YXJPageControl/YXJPageController/DIYPageView.swift
4
706
// // DIYPageView.swift // YXJPageControllerTest // // Created by yuanxiaojun on 16/8/11. // Copyright © 2016年 袁晓钧. All rights reserved. // import UIKit import YXJPageController_iOS class DIYPageView: YXJAbstractDotView { override init(frame: CGRect) { super.init(frame: frame) self.backgroundColor = UIColor.blue } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) self.backgroundColor = UIColor.blue } override func changeActivityState(_ active: Bool) { if active == true { self.backgroundColor = UIColor.red } else { self.backgroundColor = UIColor.blue } } }
apache-2.0
zendobk/SwiftUtils
Tests/Data/TestView.swift
1
181
// // TestView.swift // SwiftUtils // // Created by DaoNV on 9/4/16. // Copyright © 2016 Asian Tech Co., Ltd. All rights reserved. // import UIKit class TestView: UIView { }
apache-2.0
hejunbinlan/RealmResultsController
Example/RealmResultsController-iOSTests/RealmSectionSpec.swift
1
5016
// // RealmSectionSpec.swift // RealmResultsController // // Created by Isaac Roldan on 7/8/15. // Copyright © 2015 Redbooth. // import Foundation import Quick import Nimble import RealmSwift @testable import RealmResultsController class SectionSpec: QuickSpec { override func spec() { var sortDescriptors: [NSSortDescriptor]! var section: Section<Task>! var openTask: Task! var resolvedTask: Task! beforeSuite { sortDescriptors = [NSSortDescriptor(key: "name", ascending: false)] section = Section<Task>(keyPath: "keyPath", sortDescriptors: sortDescriptors) openTask = Task() openTask.id = 1500 openTask.name = "aatest" openTask.resolved = false resolvedTask = Task() resolvedTask.id = 1501 resolvedTask.name = "bbtest" resolvedTask.resolved = false } describe("create a Section object") { it("has everything you need to get started") { expect(section.keyPath).to(equal("keyPath")) expect(section.sortDescriptors).to(equal(sortDescriptors)) } } describe("insertSorted(object:)") { var index: Int! context("when the section is empty") { it ("beforeAll") { index = section.insertSorted(openTask) } it("a has one item") { expect(section.objects.count).to(equal(1)) } it("item has index 0") { expect(index).to(equal(0)) } } context("when the section is not empty") { it("beforeAll") { index = section.insertSorted(resolvedTask) } it("has two items") { expect(section.objects.count).to(equal(2)) } it("has index 0") { // beacuse of the sortDescriptor expect(index).to(equal(0)) } } } describe("delete(object:)") { var originalIndex: Int! var index: Int! context("when the object exists in section") { beforeEach { section = Section<Task>(keyPath: "keyPath", sortDescriptors: sortDescriptors) section.insertSorted(resolvedTask) originalIndex = section.insertSorted(openTask) index = section.delete(openTask) } it("removes it from array") { expect(section.objects.containsObject(openTask)).to(beFalsy()) } it("returns the index of the deleted object") { expect(index).to(equal(originalIndex)) } } context("the object does not exists in section") { var anotherTask: Task! beforeEach { section = Section<Task>(keyPath: "keyPath", sortDescriptors: sortDescriptors) section.insertSorted(resolvedTask) section.insertSorted(openTask) anotherTask = Task() index = section.delete(anotherTask) } it("returns index -1") { expect(index).to(equal(-1)) } } } describe("deleteOutdatedObject(object:)") { var originalIndex: Int! var index: Int! context("when the object exists in section") { beforeEach { section = Section<Task>(keyPath: "keyPath", sortDescriptors: sortDescriptors) section.insertSorted(resolvedTask) originalIndex = section.insertSorted(openTask) index = section.deleteOutdatedObject(openTask) } it("removes it from array") { expect(section.objects.containsObject(openTask)).to(beFalsy()) } it("returns the index of the deleted object") { expect(index).to(equal(originalIndex)) } } var anotherTask: Task! context("the object does not exists in section") { beforeEach { section = Section<Task>(keyPath: "keyPath", sortDescriptors: sortDescriptors) section.insertSorted(resolvedTask) section.insertSorted(openTask) anotherTask = Task() index = section.deleteOutdatedObject(anotherTask) } it("returns index -1") { expect(index).to(equal(-1)) } } } } }
mit
GuanshanLiu/Animation-Timing
Animation TimingTests/Animation_TimingTests.swift
1
929
// // Animation_TimingTests.swift // Animation TimingTests // // Created by Guanshan Liu on 21/1/15. // Copyright (c) 2015 Guanshan Liu. All rights reserved. // import UIKit import XCTest class Animation_TimingTests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. } 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() { // This is an example of a functional test case. XCTAssert(true, "Pass") } func testPerformanceExample() { // This is an example of a performance test case. self.measureBlock() { // Put the code you want to measure the time of here. } } }
mit
ksco/swift-algorithm-club-cn
Binary Search Tree/Solution 1/BinarySearchTree.playground/Contents.swift
1
1210
//: Playground - noun: a place where people can play let tree = BinarySearchTree<Int>(value: 7) tree.insert(2) tree.insert(5) tree.insert(10) tree.insert(9) tree.insert(1) tree tree.debugDescription let tree2 = BinarySearchTree<Int>(array: [7, 2, 5, 10, 9, 1]) tree.search(5) tree.search(2) tree.search(7) tree.search(6) tree.traverseInOrder { value in print(value) } tree.toArray() tree.minimum() tree.maximum() if let node2 = tree.search(2) { node2.remove() node2 print(tree) } tree.height() tree.predecessor() tree.successor() if let node10 = tree.search(10) { node10.depth() // 1 node10.height() // 1 node10.predecessor() node10.successor() // nil } if let node9 = tree.search(9) { node9.depth() // 2 node9.height() // 0 node9.predecessor() node9.successor() } if let node1 = tree.search(1) { // This makes it an invalid binary search tree because 100 is greater // than the root, 7, and so must be in the right branch not in the left. tree.isBST(minValue: Int.min, maxValue: Int.max) // true node1.insert(100) tree.search(100) // nil tree.isBST(minValue: Int.min, maxValue: Int.max) // false }
mit
serp1412/LazyTransitions
LazyTransitions/TransitionCombinator.swift
1
3166
// // TransitionCombinator.swift // LazyTransitions // // Created by BeardWare on 12/11/16. // Copyright © 2016 BeardWare. All rights reserved. // import Foundation public class TransitionCombinator: TransitionerType { public weak var delegate: TransitionerDelegate? public var animator: TransitionAnimatorType { return currentTransitioner?.animator ?? dismissAnimator } public var interactor: TransitionInteractor? { return currentTransitioner?.interactor } public var allowedOrientations: [TransitionOrientation]? { didSet { updateAnimatorsAllowedOrientations() } } public private(set) var transitioners: [TransitionerType] { didSet { updateTransitionersDelegate() updateAnimatorsAllowedOrientations() } } fileprivate var currentTransitioner: TransitionerType? fileprivate let dismissAnimator: TransitionAnimatorType fileprivate var delayedRemove: (() -> ())? fileprivate var isTransitionInProgress: Bool { return currentTransitioner != nil } public convenience init(defaultAnimator: TransitionAnimatorType = DismissAnimator(orientation: .topToBottom), transitioners: TransitionerType...) { self.init(defaultAnimator: defaultAnimator, transitioners: transitioners) } public init(defaultAnimator: TransitionAnimatorType = DismissAnimator(orientation: .topToBottom), transitioners: [TransitionerType]) { self.dismissAnimator = defaultAnimator self.transitioners = transitioners updateTransitionersDelegate() } public func add(_ transitioner: TransitionerType) { transitioners.append(transitioner) } public func remove(_ transitioner: TransitionerType) { let remove: (() -> ()) = { [weak self] in self?.transitioners = self?.transitioners.filter { $0 !== transitioner } ?? [] } isTransitionInProgress ? delayedRemove = remove : remove() } fileprivate func updateTransitionersDelegate() { transitioners.forEach{ $0.delegate = self } } fileprivate func updateAnimatorsAllowedOrientations() { allowedOrientations.apply { orientations in transitioners.forEach { $0.animator.allowedOrientations = orientations } } } } extension TransitionCombinator: TransitionerDelegate { public func beginTransition(with transitioner: TransitionerType) { currentTransitioner = transitioner delegate?.beginTransition(with: transitioner) } public func finishedInteractiveTransition(_ completed: Bool) { currentTransitioner = nil delayedRemove?() delayedRemove = nil delegate?.finishedInteractiveTransition(completed) } } extension TransitionCombinator { public func add(_ transitioners: [TransitionerType]) { transitioners.forEach { transitioner in add(transitioner) } } public func remove(_ transitioners: [TransitionerType]) { transitioners.forEach { transitioner in remove(transitioner) } } }
bsd-2-clause
thongtran715/Find-Friends
MapKitTutorial/ViewController.swift
1
11042
// // ViewController.swift // MapKitTutorial // // Created by Robert Chen on 12/23/15. // Copyright © 2015 Thorn Technologies. All rights reserved. // import UIKit import MapKit import Social import MessageUI protocol HandleMapSearch { func dropPinZoomIn(placemark:MKPlacemark) } class ViewController : UIViewController { @IBOutlet var shareOutlet: UIBarButtonItem! var selectedPin:MKPlacemark? = nil var resultSearchController:UISearchController? = nil let locationManager = CLLocationManager() @IBOutlet weak var mapView: MKMapView! override func viewDidLoad() { super.viewDidLoad() locationManager.delegate = self locationManager.desiredAccuracy = kCLLocationAccuracyBest locationManager.requestWhenInUseAuthorization() locationManager.requestLocation() let locationSearchTable = storyboard!.instantiateViewControllerWithIdentifier("LocationSearchTable") as! LocationSearchTable resultSearchController = UISearchController(searchResultsController: locationSearchTable) resultSearchController?.searchResultsUpdater = locationSearchTable let searchBar = resultSearchController!.searchBar searchBar.sizeToFit() searchBar.placeholder = "Search for places" navigationItem.titleView = resultSearchController?.searchBar resultSearchController?.hidesNavigationBarDuringPresentation = false resultSearchController?.dimsBackgroundDuringPresentation = true definesPresentationContext = true locationSearchTable.mapView = mapView locationSearchTable.handleMapSearchDelegate = self // // var temp: CLLocationCoordinate2D = CLLocationCoordinate2D(latitude: -33.952850, longitude: 151.138301) // // let annotation = MyAnnotation(coordinate: temp) // // annotation.title = "test" // // // // mapView.addAnnotation(annotation) // } func getDirections(){ if let selectedPin = selectedPin { let mapItem = MKMapItem(placemark: selectedPin) let launchOptions = [MKLaunchOptionsDirectionsModeKey : MKLaunchOptionsDirectionsModeDriving] mapItem.openInMapsWithLaunchOptions(launchOptions) } // // let latitude = -33.952850 // let longitude = 151.138301 // let location = CLLocation(latitude: latitude, longitude: longitude) // // // CLGeocoder().reverseGeocodeLocation(location) { (placemark, error) in // // if placemark?.count > 0 // { // let pinForAppleMaps = placemark![0] as CLPlacemark // // let mapItem = MKMapItem(placemark: MKPlacemark(coordinate: pinForAppleMaps.location!.coordinate, addressDictionary: pinForAppleMaps.addressDictionary as! [String:AnyObject]?)) // // let launchOptions = [MKLaunchOptionsDirectionsModeKey : MKLaunchOptionsDirectionsModeDriving] // mapItem.openInMapsWithLaunchOptions(launchOptions) // // // // } // } } @IBAction func shareButton(sender: AnyObject) { locationManager.stopUpdatingLocation() CLGeocoder().reverseGeocodeLocation(self.locationManager.location!) { (placemarks, error) in if error != nil { print("error" + (error?.localizedDescription)!) } if placemarks?.count > 0 { let p = placemarks![0] as CLPlacemark let shareActionSheet = UIAlertController(title: nil, message: "Share with", preferredStyle: .ActionSheet) let twitterShareAction = UIAlertAction(title: "Twitter", style: UIAlertActionStyle.Default, handler: { (action) in if SLComposeViewController.isAvailableForServiceType(SLServiceTypeTwitter) { let tweetComposer = SLComposeViewController(forServiceType: SLServiceTypeTwitter) tweetComposer.setInitialText("Hey, It is my Location \n \(p.location?.coordinate.latitude) \(p.location?.coordinate.longitude)") // //tweetComposer.addImage(UIImage(data: subNote.image!)) self.presentViewController(tweetComposer, animated: true, completion: nil) } else { self.alert(extendMessage: "Twitter Unavailable", extendTitle: "Please log in to Twitter Account") } }) let FacebookShareAction = UIAlertAction(title: "Facebook", style: UIAlertActionStyle.Default, handler: { (action) in if SLComposeViewController.isAvailableForServiceType(SLServiceTypeFacebook) { let FacebookComposer = SLComposeViewController(forServiceType: SLServiceTypeFacebook) FacebookComposer.setInitialText("Hey, It is my Location \n \(p.location!.coordinate.latitude) \n \(p.location!.coordinate.longitude)") // FacebookComposer.addImage(UIImage(data: subNote.image!)) self.presentViewController(FacebookComposer, animated: true, completion: nil) } else { self.alert(extendMessage: "Facebook Unavailable", extendTitle: "Please log in to Facebook Account") } }) let cancel = UIAlertAction(title: "Cancel", style: UIAlertActionStyle.Cancel, handler: nil) shareActionSheet.addAction(twitterShareAction) shareActionSheet.addAction(FacebookShareAction) shareActionSheet.addAction(cancel) // This must have for ipad stimulator shareActionSheet.popoverPresentationController?.sourceView = self.view self.presentViewController(shareActionSheet, animated: true, completion: nil) } } } // Alert function func alert(extendMessage dataMessage: String, extendTitle dataTitle: String){ let alertController = UIAlertController(title: dataMessage, message: dataTitle, preferredStyle: .Alert) let Cancel = UIAlertAction(title: "Cancel", style: .Cancel, handler: nil) alertController.addAction(Cancel) self.presentViewController(alertController, animated: true, completion: nil) } // // func displayLocationinfo(placeMark : CLPlacemark) // { // self.locationManager.stopUpdatingLocation() // print(placeMark.administrativeArea!) // print(placeMark.postalCode!) // print(placeMark.country!) // print(placeMark.location?.coordinate.latitude) // print(placeMark.location?.coordinate.longitude) // print(placeMark.locality!) // } } extension ViewController : CLLocationManagerDelegate { func locationManager(manager: CLLocationManager, didChangeAuthorizationStatus status: CLAuthorizationStatus) { if status == .AuthorizedWhenInUse { locationManager.requestLocation() } } func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { if let UserLocation = locations.first { let span = MKCoordinateSpanMake(0.05, 0.05) let region = MKCoordinateRegion(center: UserLocation.coordinate, span: span) mapView.setRegion(region, animated: true) } // //let UserLocation = locations[0] // // let latitude: CLLocationDegrees = UserLocation.coordinate.latitude // let longtitude: CLLocationDegrees = UserLocation.coordinate.longitude // let ladelta: CLLocationDegrees = 1 // let lodelta: CLLocationDegrees = 1 // // // these 2 must be implemented // let span: MKCoordinateSpan = MKCoordinateSpanMake(ladelta, lodelta) // let coordi : CLLocationCoordinate2D = CLLocationCoordinate2DMake(latitude, longtitude) // // let region: MKCoordinateRegion = MKCoordinateRegionMake(coordi, span) // // mapView.setRegion(region, animated: true) // } func locationManager(manager: CLLocationManager, didFailWithError error: NSError) { alert(extendMessage: "Erro", extendTitle: "Can't load location") } } extension ViewController: HandleMapSearch { func dropPinZoomIn(placemark:MKPlacemark){ // cache the pin selectedPin = placemark // clear existing pins mapView.removeAnnotations(mapView.annotations) let annotation = MKPointAnnotation() annotation.coordinate = placemark.coordinate annotation.title = placemark.name if let city = placemark.locality, let state = placemark.administrativeArea, let addressNumber = placemark.subThoroughfare, let street = placemark.thoroughfare { annotation.subtitle = "\(addressNumber) \(street), \(city), \(state)" } mapView.addAnnotation(annotation) let span = MKCoordinateSpanMake(0.05, 0.05) let region = MKCoordinateRegionMake(placemark.coordinate, span) mapView.setRegion(region, animated: true) } } extension ViewController : MKMapViewDelegate { func mapView(mapView: MKMapView, viewForAnnotation annotation: MKAnnotation) -> MKAnnotationView?{ if annotation is MKUserLocation { //return nil so map view draws "blue dot" for standard user location return nil } let reuseId = "pin" var pinView = mapView.dequeueReusableAnnotationViewWithIdentifier(reuseId) as? MKPinAnnotationView pinView = MKPinAnnotationView(annotation: annotation, reuseIdentifier: reuseId) pinView?.pinTintColor = UIColor.orangeColor() pinView?.canShowCallout = true let smallSquare = CGSize(width: 30, height: 30) let button = UIButton(frame: CGRect(origin: CGPointZero, size: smallSquare)) button.setBackgroundImage(UIImage(named: "car"), forState: .Normal) button.addTarget(self, action: #selector(ViewController.getDirections), forControlEvents: .TouchUpInside) pinView?.leftCalloutAccessoryView = button return pinView } }
mit
nguyenantinhbk77/practice-swift
Games/CookieCrunch/CookieCrunch/CookieCrunch/Chain.swift
3
1304
// // Chain.swift // CookieCrunch // // Created by Domenico on 11/15/14. // class Chain: Hashable, Printable { // List of cookies: it is an array because you want to remember the order of the cookies var cookies = [Cookie]() // Chain type enum ChainType: Printable { case Horizontal case Vertical var description: String { switch self { case .Horizontal: return "Horizontal" case .Vertical: return "Vertical" } } } var chainType: ChainType init(chainType: ChainType) { self.chainType = chainType } func addCookie(cookie: Cookie) { cookies.append(cookie) } func firstCookie() -> Cookie { return cookies[0] } func lastCookie() -> Cookie { return cookies[cookies.count - 1] } var length: Int { return cookies.count } var description: String { return "type:\(chainType) cookies:\(cookies)" } var hashValue: Int { // exclusive-or on the hash values of all the cookies in the chain return reduce(cookies, 0) { $0.hashValue ^ $1.hashValue } } } func ==(lhs: Chain, rhs: Chain) -> Bool { return lhs.cookies == rhs.cookies }
mit
natecook1000/swift-compiler-crashes
crashes-duplicates/16743-swift-sourcemanager-getmessage.swift
11
236
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing for { func i { let a { protocol b { extension Array { class case ,
mit
HTWDD/htwcampus
HTWDD/Core/Extensions/Array_TestCase.swift
2
381
// // Array_TestCase.swift // HTWDD // // Created by Benjamin Herzog on 20/03/2017. // Copyright © 2017 HTW Dresden. All rights reserved. // import XCTest @testable import HTWDD class Array_TestCase: XCTestCase { func test_safeSubscript() { let array = [1, 2, 3] XCTAssertEqual(array[safe: 0], 1) XCTAssertNil(array[safe: array.count]) } }
mit
natecook1000/swift-compiler-crashes
crashes-duplicates/05815-swift-archetypebuilder-resolvearchetype.swift
11
253
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing class B<e) -> Void{ let end = c<T where T: T, g = "\() { } struct c<T where T.e = e
mit
jdbateman/VirtualTourist
VirtualTourist/CoreDataStackManager.swift
1
5186
/*! @header CoreDataStackManager.swift VirtualTourist The CoreDataStackManager class provides access to the Core Data stack, abstracting interaction with the sqlite store. Use it to access the Core Data context and to persist the context. @author John Bateman. Created on 9/16/15 @copyright Copyright (c) 2015 John Bateman. All rights reserved. */ import Foundation import CoreData // MARK: - Core Data stack private let SQLITE_FILE_NAME = "VirtualTourist.sqlite" class CoreDataStackManager { /* Get a shared instance of the stack manager. */ class func sharedInstance() -> CoreDataStackManager { struct Static { static let instance = CoreDataStackManager() } return Static.instance } /* true indicates a serious error occurred. Get error status info from . false indicates no serious error has occurred. */ var bCoreDataSeriousError = false struct ErrorInfo { var code: Int = 0 var message: String = "" } var seriousErrorInfo: ErrorInfo = ErrorInfo() lazy var applicationDocumentsDirectory: NSURL = { // The directory the application uses to store the Core Data store file. This code uses a directory named "self.JohnBateman.VirtualTourist" in the application's documents Application Support directory. let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask) return urls[urls.count-1] as! NSURL }() lazy var managedObjectModel: NSManagedObjectModel = { // The managed object model for the application. This property is not optional. It is a fatal error for the application not to be able to find and load its model. let modelURL = NSBundle.mainBundle().URLForResource("VirtualTourist", withExtension: "momd")! return NSManagedObjectModel(contentsOfURL: modelURL)! }() lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator? = { // The persistent store coordinator for the application. This implementation creates and return a coordinator, having added the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail. // Create the coordinator and store var coordinator: NSPersistentStoreCoordinator? = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel) let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent(SQLITE_FILE_NAME) var error: NSError? = nil var failureReason = "There was an error creating or loading the application's saved data." if coordinator!.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: nil, error: &error) == nil { coordinator = nil // Report any error we got. var dict = [String: AnyObject]() dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data" dict[NSLocalizedFailureReasonErrorKey] = failureReason dict[NSUnderlyingErrorKey] = error error = NSError(domain: VTError.Constants.ERROR_DOMAIN, code: VTError.ErrorCodes.CORE_DATA_INIT_ERROR.rawValue, userInfo: dict) NSLog("Unresolved error \(error), \(error!.userInfo)") // flag fatal Core Data error self.seriousErrorInfo = ErrorInfo(code: VTError.ErrorCodes.CORE_DATA_INIT_ERROR.rawValue, message: "Failed to initialize the application's saved data") self.bCoreDataSeriousError = true } return coordinator }() lazy var managedObjectContext: NSManagedObjectContext? = { // Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail. let coordinator = self.persistentStoreCoordinator if coordinator == nil { return nil } // Suggested to make 1 line change the boilerplate code generated by Xcode: https://discussions.udacity.com/t/not-able-to-pass-specification-with-code-taught-in-the-lessons/31961/6 var managedObjectContext = NSManagedObjectContext(concurrencyType: .MainQueueConcurrencyType) managedObjectContext.persistentStoreCoordinator = coordinator return managedObjectContext }() // MARK: - Core Data Saving support func saveContext () { if let moc = self.managedObjectContext { var error: NSError? = nil if moc.hasChanges && !moc.save(&error) { // Replace this implementation with code to handle the error appropriately. // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. NSLog("Unresolved error \(error), \(error!.userInfo)") abort() } } } }
mit
microlimbic/Matrix
Matrix/Sources/Supporting Type/ScalarType.swift
1
771
// // ScalarType.swift // TWMLMatrix // // Created by Grady Zhuo on 2015/9/8. // Copyright © 2015年 Limbic. All rights reserved. // import Accelerate //MARK: Scalar Type Redefined public struct ScalarType: RawRepresentable { public typealias RawValue = la_scalar_type_t internal var value:RawValue /// Convert from a value of `RawValue`, succeeding unconditionally. public init(rawValue: RawValue){ self.value = rawValue } public var rawValue: RawValue { return value } public static let Default = ScalarType.Double public static let Float = ScalarType(rawValue: la_scalar_type_t(LA_SCALAR_TYPE_FLOAT)) public static let Double = ScalarType(rawValue: la_scalar_type_t(LA_SCALAR_TYPE_DOUBLE)) }
mit
Fenrikur/ef-app_ios
Domain Model/EurofurenceModel/Public/Builder/EurofurenceSessionBuilder.swift
1
7637
import Foundation public class EurofurenceSessionBuilder { public struct Mandatory { public var conventionIdentifier: ConventionIdentifier public var conventionStartDateRepository: ConventionStartDateRepository public var shareableURLFactory: ShareableURLFactory public init(conventionIdentifier: ConventionIdentifier, conventionStartDateRepository: ConventionStartDateRepository, shareableURLFactory: ShareableURLFactory) { self.conventionIdentifier = conventionIdentifier self.conventionStartDateRepository = conventionStartDateRepository self.shareableURLFactory = shareableURLFactory } } private let conventionIdentifier: ConventionIdentifier private let conventionStartDateRepository: ConventionStartDateRepository private let shareableURLFactory: ShareableURLFactory private var userPreferences: UserPreferences private var dataStoreFactory: DataStoreFactory private var remoteNotificationsTokenRegistration: RemoteNotificationsTokenRegistration? private var clock: Clock private var credentialStore: CredentialStore private var api: API private var timeIntervalForUpcomingEventsSinceNow: TimeInterval private var imageRepository: ImageRepository private var significantTimeChangeAdapter: SignificantTimeChangeAdapter? private var urlOpener: URLOpener? private var collectThemAllRequestFactory: CollectThemAllRequestFactory private var longRunningTaskManager: LongRunningTaskManager? private var mapCoordinateRender: MapCoordinateRender? private var forceRefreshRequired: ForceRefreshRequired private var companionAppURLRequestFactory: CompanionAppURLRequestFactory private var refreshCollaboration: RefreshCollaboration = DoNothingRefreshCollaboration() public init(mandatory: Mandatory) { self.conventionIdentifier = mandatory.conventionIdentifier self.conventionStartDateRepository = mandatory.conventionStartDateRepository self.shareableURLFactory = mandatory.shareableURLFactory userPreferences = UserDefaultsPreferences() dataStoreFactory = CoreDataStoreFactory() let jsonSession = URLSessionBasedJSONSession.shared let apiUrl = CIDAPIURLProviding(conventionIdentifier: conventionIdentifier) api = JSONAPI(jsonSession: jsonSession, apiUrl: apiUrl) clock = SystemClock.shared credentialStore = KeychainCredentialStore() timeIntervalForUpcomingEventsSinceNow = 3600 imageRepository = PersistentImageRepository() collectThemAllRequestFactory = DefaultCollectThemAllRequestFactory() forceRefreshRequired = UserDefaultsForceRefreshRequired() companionAppURLRequestFactory = HardcodedCompanionAppURLRequestFactory() } @discardableResult public func with(_ userPreferences: UserPreferences) -> EurofurenceSessionBuilder { self.userPreferences = userPreferences return self } @discardableResult public func with(_ dataStoreFactory: DataStoreFactory) -> EurofurenceSessionBuilder { self.dataStoreFactory = dataStoreFactory return self } @discardableResult public func with(_ remoteNotificationsTokenRegistration: RemoteNotificationsTokenRegistration) -> EurofurenceSessionBuilder { self.remoteNotificationsTokenRegistration = remoteNotificationsTokenRegistration return self } @discardableResult public func with(_ clock: Clock) -> EurofurenceSessionBuilder { self.clock = clock return self } @discardableResult public func with(_ credentialStore: CredentialStore) -> EurofurenceSessionBuilder { self.credentialStore = credentialStore return self } @discardableResult public func with(timeIntervalForUpcomingEventsSinceNow: TimeInterval) -> EurofurenceSessionBuilder { self.timeIntervalForUpcomingEventsSinceNow = timeIntervalForUpcomingEventsSinceNow return self } @discardableResult public func with(_ api: API) -> EurofurenceSessionBuilder { self.api = api return self } @discardableResult public func with(_ imageRepository: ImageRepository) -> EurofurenceSessionBuilder { self.imageRepository = imageRepository return self } @discardableResult public func with(_ significantTimeChangeAdapter: SignificantTimeChangeAdapter) -> EurofurenceSessionBuilder { self.significantTimeChangeAdapter = significantTimeChangeAdapter return self } @discardableResult public func with(_ urlOpener: URLOpener) -> EurofurenceSessionBuilder { self.urlOpener = urlOpener return self } @discardableResult public func with(_ collectThemAllRequestFactory: CollectThemAllRequestFactory) -> EurofurenceSessionBuilder { self.collectThemAllRequestFactory = collectThemAllRequestFactory return self } @discardableResult public func with(_ longRunningTaskManager: LongRunningTaskManager) -> EurofurenceSessionBuilder { self.longRunningTaskManager = longRunningTaskManager return self } @discardableResult public func with(_ mapCoordinateRender: MapCoordinateRender) -> EurofurenceSessionBuilder { self.mapCoordinateRender = mapCoordinateRender return self } @discardableResult public func with(_ forceRefreshRequired: ForceRefreshRequired) -> EurofurenceSessionBuilder { self.forceRefreshRequired = forceRefreshRequired return self } @discardableResult public func with(_ companionAppURLRequestFactory: CompanionAppURLRequestFactory) -> EurofurenceSessionBuilder { self.companionAppURLRequestFactory = companionAppURLRequestFactory return self } @discardableResult public func with(_ refreshCollaboration: RefreshCollaboration) -> EurofurenceSessionBuilder { self.refreshCollaboration = refreshCollaboration return self } public func build() -> EurofurenceSession { return ConcreteSession(conventionIdentifier: conventionIdentifier, api: api, userPreferences: userPreferences, dataStoreFactory: dataStoreFactory, remoteNotificationsTokenRegistration: remoteNotificationsTokenRegistration, clock: clock, credentialStore: credentialStore, conventionStartDateRepository: conventionStartDateRepository, timeIntervalForUpcomingEventsSinceNow: timeIntervalForUpcomingEventsSinceNow, imageRepository: imageRepository, significantTimeChangeAdapter: significantTimeChangeAdapter, urlOpener: urlOpener, collectThemAllRequestFactory: collectThemAllRequestFactory, longRunningTaskManager: longRunningTaskManager, mapCoordinateRender: mapCoordinateRender, forceRefreshRequired: forceRefreshRequired, companionAppURLRequestFactory: companionAppURLRequestFactory, refreshCollaboration: refreshCollaboration, shareableURLFactory: shareableURLFactory) } }
mit
jyq52787/NeteaseNews
News/News/regexViewController.swift
1
1480
// // ViewController.swift // 正则表达式 // // Created by 贾永强 on 15/10/26. // Copyright © 2015年 heima. All rights reserved. // import UIKit let string: String = "哈哈 http://www.itheima.com 哈哈哈" class regexViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() let ranges = urlRanges() print((string as NSString).substringWithRange(ranges![0])) } private func urlRanges() -> [NSRange]? { //需求过滤出 字符串:"哈哈 http://www.itheima.com 哈哈哈" 中的网址部分 // 提示:开发中,如果需要特殊的正则,可以百度 例如网址\手机号码\email等 let pattern = "[a-zA-Z]*://[a-zA-Z0-9/\\.]*" let regex = try! NSRegularExpression(pattern: pattern, options: NSRegularExpressionOptions.DotMatchesLineSeparators) // 用正则匹配 url 内容, 如果一个文本里可能有多个网址连接,所以用matchesInString,此方法是NSRegularExpression的扩展方法 let results = regex.matchesInString(string, options: NSMatchingOptions(rawValue: 0), range: NSMakeRange(0, string.characters.count)) // 遍历数组,生成结果 var ranges = [NSRange]() for r in results { ranges.append(r.rangeAtIndex(0)) } return ranges } }
mit
nbkey/DouYuTV
DouYu/DouYu/Classes/Main/View/CollectionPrettyCell.swift
1
518
// // CollectionPrettyCell.swift // DouYu // // Created by 吉冠坤 on 2017/7/25 // Copyright © 2017年 吉冠坤. All rights reserved. // import UIKit import Kingfisher class CollectionPrettyCell: CollectionBaseCell { @IBOutlet weak var cityButton: UIButton! override var anchor :AnchorModel? { didSet { //1.通知父类 super.anchor = anchor //3.显示所在城市 cityButton.setTitle(anchor?.anchor_city, for: .normal) } } }
mit
iscriptology/swamp
Example/Pods/CryptoSwift/Sources/CryptoSwift/Operators.swift
3
785
// // Operators.swift // CryptoSwift // // Created by Marcin Krzyzanowski on 02/09/14. // Copyright (c) 2014 Marcin Krzyzanowski. All rights reserved. // /* Bit shifting with overflow protection using overflow operator "&". Approach is consistent with standard overflow operators &+, &-, &*, &/ and introduce new overflow operators for shifting: &<<, &>> Note: Works with unsigned integers values only Usage var i = 1 // init var j = i &<< 2 //shift left j &<<= 2 //shift left and assign @see: https://medium.com/@krzyzanowskim/swiftly-shift-bits-and-protect-yourself-be33016ce071 */ infix operator &<<= : BitwiseShiftPrecedence infix operator &<< : BitwiseShiftPrecedence infix operator &>>= : BitwiseShiftPrecedence infix operator &>> : BitwiseShiftPrecedence
mit
TMTBO/TTAMusicPlayer
TTAMusicPlayer/TTAMusicPlayerUITests/TTAMusicPlayerUITests.swift
1
1251
// // TTAMusicPlayerUITests.swift // TTAMusicPlayerUITests // // Created by ys on 16/11/22. // Copyright © 2016年 YS. All rights reserved. // import XCTest class TTAMusicPlayerUITests: 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. } }
mit
OpenVidu/openvidu-tutorials
openvidu-ionic/ios/App/App/AppDelegate.swift
4
3480
import UIKit import Capacitor @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: 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:. } func application(_ app: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey: Any] = [:]) -> Bool { // Called when the app was launched with a url. Feel free to add additional processing here, // but if you want the App API to support tracking app url opens, make sure to keep this call return ApplicationDelegateProxy.shared.application(app, open: url, options: options) } func application(_ application: UIApplication, continue userActivity: NSUserActivity, restorationHandler: @escaping ([UIUserActivityRestoring]?) -> Void) -> Bool { // Called when the app was launched with an activity, including Universal Links. // Feel free to add additional processing here, but if you want the App API to support // tracking app url opens, make sure to keep this call return ApplicationDelegateProxy.shared.application(application, continue: userActivity, restorationHandler: restorationHandler) } override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { super.touchesBegan(touches, with: event) let statusBarRect = UIApplication.shared.statusBarFrame guard let touchPoint = event?.allTouches?.first?.location(in: self.window) else { return } if statusBarRect.contains(touchPoint) { NotificationCenter.default.post(name: .capacitorStatusBarTapped, object: nil) } } }
apache-2.0
ahoppen/swift
test/Serialization/witnesstable-function-deserialization.swift
40
382
// RUN: %empty-directory(%t) // RUN: %target-swift-frontend -emit-module -O -module-name Swift -module-link-name swiftCore -parse-as-library -parse-stdlib -emit-module %S/Inputs/witnesstable-function-deserialization-input.swift -o %t/Swift.swiftmodule -sil-inline-threshold 10 // RUN: %target-swift-frontend -I %t %s -emit-sil -o - -O import Swift var x = X() makeZDoSomething(x)
apache-2.0
cozkurt/coframework
COFramework/Sample/AppDelegate.swift
1
1346
// // AppDelegate.swift // Sample // // Created by Ozkurt, Cenker on 8/1/22. // import UIKit @main 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. } }
gpl-3.0
danieleggert/HidingNavigationBar
HidingNavigationBarSample/HidingNavigationBarSample/HidingNavTabViewController.swift
1
2700
// // TableViewController.swift // HidingNavigationBarSample // // Created by Tristan Himmelman on 2015-05-01. // Copyright (c) 2015 Tristan Himmelman. All rights reserved. // import UIKit class HidingNavTabViewController: UIViewController, UITableViewDataSource, UITableViewDelegate { let identifier = "cell" var hidingNavBarManager: HidingNavigationBarManager? var tableView: UITableView! var toolbar: UIToolbar! override func viewDidLoad() { super.viewDidLoad() tableView = UITableView(frame: view.bounds) tableView.dataSource = self tableView.delegate = self tableView.registerClass(UITableViewCell.classForCoder(), forCellReuseIdentifier: identifier) view.addSubview(tableView) let cancelButton = UIBarButtonItem(title: "Cancel", style: .Plain, target: self, action: Selector("cancelButtonTouched")) navigationItem.leftBarButtonItem = cancelButton hidingNavBarManager = HidingNavigationBarManager(viewController: self, scrollView: tableView) if let tabBar = navigationController?.tabBarController?.tabBar { hidingNavBarManager?.manageBottomBar(tabBar) tabBar.barTintColor = UIColor(white: 230/255, alpha: 1) } } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) hidingNavBarManager?.viewWillAppear(animated) } override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() hidingNavBarManager?.viewDidLayoutSubviews() } override func viewWillDisappear(animated: Bool) { super.viewWillDisappear(animated) hidingNavBarManager?.viewWillDisappear(animated) } func cancelButtonTouched(){ navigationController?.dismissViewControllerAnimated(true, completion: nil) } // MARK: UITableViewDelegate func scrollViewShouldScrollToTop(scrollView: UIScrollView) -> Bool { hidingNavBarManager?.shouldScrollToTop() return true } // MARK: - Table view data source func numberOfSectionsInTableView(tableView: UITableView) -> Int { // #warning Potentially incomplete method implementation. // Return the number of sections. return 1 } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // #warning Incomplete method implementation. // Return the number of rows in the section. return 100 } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier(identifier, forIndexPath: indexPath) // Configure the cell... cell.textLabel?.text = "row \(indexPath.row)" cell.selectionStyle = UITableViewCellSelectionStyle.None return cell } }
mit
rwebaz/Simple-Swift-OS
photoFilters/photoFilters/photoFilters/photoFilters/photoFilters/ViewController.swift
2
1314
// // ViewController.swift // photoFilters // // Created by Robert Weber on 11/25/14. // Copyright (c) 2014 Xpadap. All rights reserved. // import UIKit class ViewController: UIViewController { @IBOutlet var photoImageView: UIImageView! //Create a memory space to render the filtered image let context = CIContext(options: nil) @IBAction func applyFilter(sender: AnyObject) { // Create an image to filter let inputImage = CIImage(image: photoImageView.image) // Create a ramdom color to pass to a filter let randomColor = [kCIInputAngleKey: (Double(arc4random_uniform(314)) / 100)] // Apply a filter to the image let filteredImage = inputImage.imageByApplyingFilter("CIHueAdjust", withInputParameters: randomColor) // Render the filtered image let renderedImage = context.createCGImage(filteredImage, fromRect: filteredImage.extent()) // Reglect the change back in the interface photoImageView.image = UIImage(CGImage: renderedImage) } override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
agpl-3.0
dclelland/HOWL
Pods/Persistable/Persistable.swift
1
2532
// // Persistable.swift // Persistable // // Created by Daniel Clelland on 4/06/16. // Copyright © 2016 Daniel Clelland. All rights reserved. // import Foundation // MARK: Persistent /// A simple struct which takes a value and persists it across sessions. public struct Persistent<T>: Persistable { /// The type of the persistent value. public typealias PersistentType = T /// Alias around `persistentValue` and `setPersistentValue:`. public var value: T { set { persistentValue = newValue } get { return persistentValue } } /// The default persistent value. public let defaultValue: T /// The key used to store the persistent value. public let persistentKey: String /** Creates a new Persistent value struct. - parameter value: The initial value. Used to register a default value with NSUserDefaults. - parameter key: The key used to set and get the value in NSUserDefaults. */ public init(value: T, key: String) { self.defaultValue = value self.persistentKey = key self.register(defaultPersistentValue: value) } /// Resets the persistent value to the default persistent value. public mutating func resetValue() { value = defaultValue } } // MARK: Persistable /// An abstract protocol which can be used to add a persistent value to existing classes and structs. public protocol Persistable { /// The type of the persistent value associatedtype PersistentType /// The key used to set the persistent value in NSUserDefaults var persistentKey: String { get } } extension Persistable { /// Set and get the persistent value from NSUserDefaults. /// /// Note that the setter is declared `nonmutating`: this is so we can implement this protocol on classes. /// Value semantics will be preserved: `didSet` will still get called when `Persistent`'s `value` is set. public var persistentValue: PersistentType { nonmutating set { UserDefaults.standard.set(newValue, forKey: persistentKey) } get { return UserDefaults.standard.object(forKey: persistentKey) as! PersistentType } } /// Register a default value with NSUserDefaults. public func register(defaultPersistentValue value: PersistentType) { UserDefaults.standard.register(defaults: [persistentKey: value]) } }
mit
taketo1024/SwiftyAlgebra
Tests/SwmCoreTests/Graph/GraphTests.swift
1
822
// // File.swift // // // Created by Taketo Sano on 2021/06/04. // import XCTest @testable import SwmCore class GraphTests: XCTestCase { func testTopologicalSort() { let G = PlainGraph(structure: [ 0: [2, 3], 1: [2], 2: [], 3: [1, 2], 4: [1] ]) guard let sorted = try? G.topologicalSort().map({ $0.id }) else { XCTFail() return } let order = (0 ... 4).map { i in sorted.firstIndex(of: i)! } print(sorted) XCTAssertTrue(order[0] < order[2]) XCTAssertTrue(order[0] < order[3]) XCTAssertTrue(order[1] < order[2]) XCTAssertTrue(order[3] < order[1]) XCTAssertTrue(order[3] < order[2]) XCTAssertTrue(order[4] < order[1]) } }
cc0-1.0
taketo1024/SwiftyAlgebra
Sources/SwmCore/Util/GraphAlgorithms.swift
1
5637
/* This source file is part of the Swift.org open source project Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors Licensed under Apache License v2.0 with Runtime Library Exception See http://swift.org/LICENSE.txt for license information See http://swift.org/CONTRIBUTORS.txt for Swift project authors */ // MEMO: // Modified global functions to methods of Sequence. // Original code: https://github.com/apple/swift-tools-support-core/blob/main/Sources/TSCBasic/GraphAlgorithms.swift public enum GraphError: Error { /// A cycle was detected in the input. case unexpectedCycle } extension Sequence where Element: Hashable { public typealias T = Element /// Compute the transitive closure of an input node set. /// /// - Note: The relation is *not* assumed to be reflexive; i.e. the result will /// not automatically include `nodes` unless present in the relation defined by /// `successors`. public func transitiveClosure( successors: (T) throws -> [T] ) rethrows -> Set<T> { var result = Set<T>() // The queue of items to recursively visit. // // We add items post-collation to avoid unnecessary queue operations. var queue = Array(self) while let node = queue.popLast() { for succ in try successors(node) { if result.insert(succ).inserted { queue.append(succ) } } } return result } /// Perform a topological sort of an graph. /// /// This function is optimized for use cases where cycles are unexpected, and /// does not attempt to retain information on the exact nodes in the cycle. /// /// - Parameters: /// - successors: A closure for fetching the successors of a particular node. /// /// - Returns: A list of the transitive closure of nodes reachable from the /// inputs, ordered such that every node in the list follows all of its /// predecessors. /// /// - Throws: GraphError.unexpectedCycle /// /// - Complexity: O(v + e) where (v, e) are the number of vertices and edges /// reachable from the input nodes via the relation. public func topologicalSort( successors: (T) throws -> [T] ) throws -> [T] { // Implements a topological sort via recursion and reverse postorder DFS. func visit(_ node: T, _ stack: inout OrderedSet<T>, _ visited: inout Set<T>, _ result: inout [T], _ successors: (T) throws -> [T]) throws { // Mark this node as visited -- we are done if it already was. if !visited.insert(node).inserted { return } // Otherwise, visit each adjacent node. for succ in try successors(node) { guard stack.append(succ) else { // If the successor is already in this current stack, we have found a cycle. // // FIXME: We could easily include information on the cycle we found here. throw GraphError.unexpectedCycle } try visit(succ, &stack, &visited, &result, successors) let popped = stack.removeLast() assert(popped == succ) } // Add to the result. result.append(node) } // FIXME: This should use a stack not recursion. var visited = Set<T>() var result = [T]() var stack = OrderedSet<T>() for node in self { precondition(stack.isEmpty) stack.append(node) try visit(node, &stack, &visited, &result, successors) let popped = stack.removeLast() assert(popped == node) } return result.reversed() } /// Finds the first cycle encountered in a graph. /// /// This method uses DFS to look for a cycle and immediately returns when a /// cycle is encounted. /// /// - Parameters: /// - successors: A closure for fetching the successors of a particular node. /// /// - Returns: nil if a cycle is not found or a tuple with the path to the start of the cycle and the cycle itself. public func findCycle( successors: (T) throws -> [T] ) rethrows -> (path: [T], cycle: [T])? { // Ordered set to hold the current traversed path. var path = OrderedSet<T>() // Function to visit nodes recursively. // FIXME: Convert to stack. func visit(_ node: T, _ successors: (T) throws -> [T]) rethrows -> (path: [T], cycle: [T])? { // If this node is already in the current path then we have found a cycle. if !path.append(node) { let index = path.firstIndex(of: node)! return (Array(path[path.startIndex..<index]), Array(path[index..<path.endIndex])) } for succ in try successors(node) { if let cycle = try visit(succ, successors) { return cycle } } // No cycle found for this node, remove it from the path. let item = path.removeLast() assert(item == node) return nil } for node in self { if let cycle = try visit(node, successors) { return cycle } } // Couldn't find any cycle in the graph. return nil } }
cc0-1.0
ben-ng/swift
validation-test/compiler_crashers_fixed/00871-swift-constraints-constraintsystem-matchtypes.swift
1
641
// This source file is part of the Swift.org open source project // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // RUN: not %target-swift-frontend %s -typecheck func f<U : P> : String = nil func f<T import Foundation return [unowned self.Type) { return self.d.c = compose(self.init(" var d where I) { print((v: NSObject { protocol d = { var e!.h = { } struct c { } } var e: A { for b = { } } }() f = nil
apache-2.0
DataArt/SmartSlides
PresentatorS/Model/ContentManager.swift
1
7872
// // ContentManager.swift // PresentatorS // // Created by Igor Litvinenko on 12/24/14. // Copyright (c) 2014 Igor Litvinenko. All rights reserved. // import Foundation import MultipeerConnectivity enum DirectoryType: Int { case Shared = 0 case Imported = 1 case Dropbox = 2 } class ContentManager: NSObject { typealias PresentationUpdate = (PresentationState) -> () typealias StopSharingType = () -> Void class var sharedInstance: ContentManager { struct Static { static let instance = ContentManager() } return Static.instance } struct PresentationState{ var presentationName = "" var currentSlide = UInt(0) var slidesAmount = 0 init(name: String, page: UInt, amount: Int){ presentationName = name currentSlide = page slidesAmount = amount } } var presentationUpdateClosure: PresentationUpdate? var onStopSharingClosure: StopSharingType? var onStartSharingClosure: PresentationUpdate? private var activePresentation: PresentationState? func startShowingPresentation(name: String, page: UInt, slidesAmount : Int){ self.activePresentation = PresentationState(name: name, page: page, amount: slidesAmount) if let presentation = self.activePresentation { self.onStartSharingClosure?(presentation) } } func stopShatingPresentation(){ self.activePresentation = nil self.onStopSharingClosure?() } func updateActivePresentationPage(page: UInt){ let shouldNotifyPageChange = self.activePresentation?.currentSlide != page self.activePresentation?.currentSlide = page if let present = self.activePresentation { if shouldNotifyPageChange { self.presentationUpdateClosure?(present) } } } func getActivePresentationState() -> PresentationState? { let state = self.activePresentation return state } func getSharedMaterials() -> [String]{ if let name = self.activePresentation?.presentationName { let pathToPresentation = NSURL.CM_pathForPresentationWithName(name) let file = File(fullPath: pathToPresentation?.path ?? "") let crc = file.md5 as String let sharedString = "\(name)/md5Hex=\(crc)" if self.activePresentation?.presentationName != nil { return [sharedString] } else { return [] } } return [] } // func getControllerPeer() -> MCPeerID{ // // return nil // } func getLocalResources() -> [String]?{ let homeDirPath = NSURL.CM_fileURLToSharedPresentationDirectory().path! let content : [String]? do { try content = NSFileManager.defaultManager().contentsOfDirectoryAtPath(homeDirPath) as [String]? var val = 4 val++ return content?.map {$0.stringByReplacingOccurrencesOfString(homeDirPath, withString: "", options: [], range: nil)} } catch { print("Error fetching content from \(homeDirPath)") return nil } } func isResourceAvailable(presentation: String, directoryType: DirectoryType) -> Bool { if directoryType == .Dropbox { if NSURL.CM_pathForPresentationWithName(presentation) != nil { return true } else { return false } } else { var array : [String] = presentation.componentsSeparatedByString("/md5Hex=") if array.count > 1 { let name = array[0] let crc = array[1] let pathToPresentation = NSURL.CM_pathForPresentationWithName(name) let file = File(fullPath: pathToPresentation?.path ?? "") if (crc == file.md5 && file.md5.characters.count > 0) { return true } else { return false } } else { return false } } } //Json Helper func JSONStringify(value: AnyObject, prettyPrinted: Bool = false) -> String { let options = prettyPrinted ? NSJSONWritingOptions.PrettyPrinted : NSJSONWritingOptions(rawValue: 0) if NSJSONSerialization.isValidJSONObject(value) { if let data = try? NSJSONSerialization.dataWithJSONObject(value, options: options) { if let string = NSString(data: data, encoding: NSUTF8StringEncoding) { return string as String } } } return "" } } extension NSURL { class func CM_fileURLToSharedPresentationDirectory() -> NSURL{ let documentDirectoryPath: String = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] return NSURL(fileURLWithPath: documentDirectoryPath) } class func CM_fileURLToImportedPresentationDirectory() -> NSURL{ let documentDirectoryURL = CM_fileURLToSharedPresentationDirectory() return documentDirectoryURL.URLByAppendingPathComponent("Inbox", isDirectory: true) } class func CM_fileURLToDropboxPresentationDirectory() -> NSURL{ let dropboxDirectoryURL = CM_fileURLToSharedPresentationDirectory().URLByAppendingPathComponent("Dropbox", isDirectory: true) let isDir = UnsafeMutablePointer<ObjCBool>.alloc(1) isDir[0] = true if !NSFileManager.defaultManager().fileExistsAtPath(dropboxDirectoryURL.path!, isDirectory: isDir) { do { try NSFileManager.defaultManager().createDirectoryAtURL(dropboxDirectoryURL, withIntermediateDirectories: false, attributes: nil) } catch let err as NSError { print("Error creating folder \(err)") } } return dropboxDirectoryURL } class func CM_pathForPresentationWithName(presentationName: String) -> NSURL? { let result = CM_fileURLToSharedPresentationDirectory().URLByAppendingPathComponent(presentationName) if NSFileManager.defaultManager().fileExistsAtPath(result.path!) { return result } else { let resultFromImported = CM_fileURLToImportedPresentationDirectory().URLByAppendingPathComponent(presentationName) if NSFileManager.defaultManager().fileExistsAtPath(resultFromImported.path!) { return resultFromImported } else { let resultFromDropbox = CM_fileURLToDropboxPresentationDirectory().URLByAppendingPathComponent(presentationName) if NSFileManager.defaultManager().fileExistsAtPath(resultFromDropbox.path!) { return resultFromDropbox } } } return nil } class func CM_pathForFramedPresentationDir(presentationURL: NSURL) -> String { var presentationName = presentationURL.lastPathComponent! if let pathComponents : [String]? = presentationURL.pathComponents { if pathComponents!.contains("Inbox") { presentationName = "Inbox_" + presentationName } } var framedPresentationDirectoryName = presentationName.stringByReplacingOccurrencesOfString(".", withString: "_", options: [], range: nil) framedPresentationDirectoryName = framedPresentationDirectoryName.stringByReplacingOccurrencesOfString(" ", withString: "_", options: [], range: nil) return NSTemporaryDirectory() + framedPresentationDirectoryName } }
mit
luispadron/GradePoint
GradePoint/Protocols/UIRubricViewDelegate.swift
1
695
// // UIAnimatedTextFieldButtonDelegate.swift // UIAnimatedTextField // // Created by Luis Padron on 9/21/16. // Copyright © 2016 Luis Padron. All rights reserved. // import UIKit /// Protocol for the rubric view protocol UIRubricViewDelegate: class { /// Notifies delegate that the plus button was touched func plusButtonTouched(_ view: UIRubricView, withState state: UIRubricViewState?) /// Notifies delgate that the rubrics valid state was updated func isRubricValidUpdated(forView view: UIRubricView) /// Notifies when the weight fields keyboard 'Calculate' button was tapped func calculateButtonWasTapped(forView view: UIRubricView, textField: UITextField) }
apache-2.0
Decybel07/L10n-swift
Source/Extensions/Date+Localizable.swift
1
4959
// // Date+Localizable.swift // L10n_swift // // Created by Adrian Bobrowski on 29.07.2017. // Copyright © 2017 Adrian Bobrowski (Decybel07), adrian071993@gmail.com. All rights reserved. // import Foundation extension Date: Localizable { /** Returns a localized `self` description. - parameter instance: The instance of `L10n` used for localization. */ public func l10n(_ instance: L10n) -> String { return self.l10n(instance, dateStyle: .medium, timeStyle: .medium, formattingContext: nil) } /** Returns a localized `self` description. - parameter instance: The instance of `L10n` used for localization. - parameter formattingContext: A formatting context used to configure the `DateFormatter.formattingContext`. */ public func l10n(_ instance: L10n, formattingContext: Formatter.Context?) -> String { return self.l10n(instance, dateStyle: .medium, timeStyle: .medium, formattingContext: formattingContext) } /** Returns a localized `self` description. - parameter instance: The instance of `L10n` used for localization. - parameter dateStyle: A style used to configure the `DateFormatter.dateStyle`. - parameter formattingContext: A formatting context used to configure the `DateFormatter.formattingContext`. */ public func l10n(_ instance: L10n = .shared, dateStyle: DateFormatter.Style, formattingContext: Formatter.Context? = nil) -> String { return self.l10n(instance, dateStyle: dateStyle, timeStyle: .none, formattingContext: formattingContext) } /** Returns a localized `self` description. - parameter instance: The instance of `L10n` used for localization. - parameter timeStyle: A style used to configure the `DateFormatter.timeStyle`. - parameter formattingContext: A formatting context used to configure the `DateFormatter.formattingContext`. */ public func l10n(_ instance: L10n = .shared, timeStyle: DateFormatter.Style, formattingContext: Formatter.Context? = nil) -> String { return self.l10n(instance, dateStyle: .none, timeStyle: timeStyle, formattingContext: formattingContext) } /** Returns a localized `self` description. - parameter instance: The instance of `L10n` used for localization. - parameter dateStyle: A style used to configure the `DateFormatter.dateStyle`. - parameter timeStyle: A style used to configure the `DateFormatter.timeStyle`. - parameter formattingContext: A formatting context used to configure the `DateFormatter.formattingContext`. */ public func l10n(_ instance: L10n = .shared, dateStyle: DateFormatter.Style, timeStyle: DateFormatter.Style, formattingContext: Formatter.Context? = nil) -> String { return self.l10n(instance) { formatter in formatter.dateStyle = dateStyle formatter.timeStyle = timeStyle formatter.formattingContext = formattingContext ?? formatter.formattingContext } } /** Returns a localized `self` description. - parameter instance: The instance of `L10n` used for localization. - parameter template: A template used to configure the `DateFormatter.dateFormat`. - parameter formattingContext: A formatting context used to configure the `DateFormatter.formattingContext`. */ public func l10n(_ instance: L10n = .shared, template: String, formattingContext: Formatter.Context? = nil) -> String { return self.l10n(instance) { formatter in formatter.dateFormat = DateFormatter.dateFormat(fromTemplate: template, options: 0, locale: instance.locale) formatter.formattingContext = formattingContext ?? formatter.formattingContext } } /** Returns a localized `self` description. - parameter instance: The instance of `L10n` used for localization. - parameter staticFormat: A format used to configure the `DateFormatter.dateFormat`. - parameter formattingContext: A formatting context used to configure the `DateFormatter.formattingContext`. */ public func l10n(_ instance: L10n = .shared, format: String, formattingContext: Formatter.Context? = nil) -> String { return self.l10n(instance) { formatter in formatter.dateFormat = format formatter.formattingContext = formattingContext ?? formatter.formattingContext } } /** Returns a localized `self` description. - parameter instance: The instance of `L10n` used for localization. - parameter closure: A closure used to configure the `DateFormatter`. - returns: A localized `self` description. */ public func l10n(_ instance: L10n = .shared, closure: (_ formatter: DateFormatter) -> Void) -> String { let formatter = DateFormatter() formatter.locale = instance.locale closure(formatter) return formatter.string(from: self) } }
mit
adrfer/swift
validation-test/stdlib/Concatenate.swift
2
2063
//===--- Concatenate.swift - Tests for lazy/eager concatenate -------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// // RUN: %target-run-simple-swift // REQUIRES: executable_test import StdlibUnittest // Also import modules which are used by StdlibUnittest internally. This // workaround is needed to link all required libraries in case we compile // StdlibUnittest with -sil-serialize-all. import SwiftPrivate #if _runtime(_ObjC) import ObjectiveC #endif var ConcatenateTests = TestSuite("ConcatenateTests") // Help the type checker (<rdar://problem/17897413> Slow type deduction) typealias X = ContiguousArray<Range<Int>> let samples: ContiguousArray<(Range<Int>, X)> = [ (0..<8, [ 1..<1, 0..<5, 7..<7, 5..<7, 7..<8 ] as X), (0..<8, [ 0..<5, 7..<7, 5..<7, 7..<8 ] as X), (0..<8, [ 1..<1, 0..<5, 7..<7, 5..<7, 7..<8, 11..<11 ] as X), (0..<8, [ 0..<5, 7..<7, 5..<7, 7..<8, 11..<11 ] as X), (0..<0, [ 11..<11 ] as X), (0..<0, [ 3..<3, 11..<11 ] as X), (0..<0, [] as X), ] let expected = ContiguousArray(0..<8) for (expected, source) in samples { ConcatenateTests.test("forward-\(source)") { checkBidirectionalCollection(expected, source.flatten()) } ConcatenateTests.test("reverse-\(source)") { // FIXME: separate 'expected' and 'reversed' variables are a workaround // for: <rdar://problem/20789500> let expected = ContiguousArray(expected.lazy.reverse()) let reversed = source.flatten().reverse() checkBidirectionalCollection(expected, reversed) } ConcatenateTests.test("sequence-\(source)") { checkSequence( ContiguousArray(expected), AnySequence(source).flatten()) } } runAllTests()
apache-2.0
fernandocastor/SillyShapes
SillyShapes/AppDelegate.swift
1
2103
// // AppDelegate.swift // SillyShapes // // Created by Fernando Castor on 03/02/15. // Copyright (c) 2015 UFPE. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> 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 throttle down OpenGL ES frame rates. 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 inactive 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:. } }
gpl-3.0
mrdepth/Neocom
Neocom/Neocom/Fitting/Implants/FittingImplantCell.swift
2
2003
// // FittingImplantCell.swift // Neocom // // Created by Artem Shimanski on 3/5/20. // Copyright © 2020 Artem Shimanski. All rights reserved. // import SwiftUI import Dgmpp struct FittingImplantCell: View { @ObservedObject var implant: DGMImplant @Environment(\.managedObjectContext) private var managedObjectContext @Environment(\.self) private var environment @State private var isActionsPresented = false var body: some View { let type = implant.type(from: managedObjectContext) return Group { HStack { Button(action: {self.isActionsPresented = true}) { HStack { if type != nil { TypeCell(type: type!) } else { Icon(Image("implant")) Text("Unknown") } Spacer() }.contentShape(Rectangle()) }.buttonStyle(PlainButtonStyle()) type.map { TypeInfoButton(type: $0) } } } .actionSheet(isPresented: $isActionsPresented) { ActionSheet(title: Text("Implant"), buttons: [.destructive(Text("Delete"), action: { (self.implant.parent as? DGMCharacter)?.remove(self.implant) }), .cancel()]) } } } #if DEBUG struct FittingImplantCell_Previews: PreviewProvider { static var previews: some View { let gang = DGMGang.testGang() let pilot = gang.pilots[0] let implant = pilot.implants.first! return NavigationView { List { FittingImplantCell(implant: implant) }.listStyle(GroupedListStyle()) } .navigationViewStyle(StackNavigationViewStyle()) .modifier(ServicesViewModifier.testModifier()) .environmentObject(gang) } } #endif
lgpl-2.1
frootloops/swift
stdlib/public/core/KeyPath.swift
1
95520
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// import SwiftShims @_inlineable // FIXME(sil-serialize-all) @_versioned // FIXME(sil-serialize-all) @_transparent internal func _abstract( methodName: StaticString = #function, file: StaticString = #file, line: UInt = #line ) -> Never { #if INTERNAL_CHECKS_ENABLED _fatalErrorMessage("abstract method", methodName, file: file, line: line, flags: _fatalErrorFlags()) #else _conditionallyUnreachable() #endif } // MARK: Type-erased abstract base classes /// A type-erased key path, from any root type to any resulting value type. @_fixed_layout // FIXME(sil-serialize-all) public class AnyKeyPath: Hashable, _AppendKeyPath { /// The root type for this key path. @_inlineable public static var rootType: Any.Type { return _rootAndValueType.root } /// The value type for this key path. @_inlineable public static var valueType: Any.Type { return _rootAndValueType.value } @_versioned // FIXME(sil-serialize-all) internal final var _kvcKeyPathStringPtr: UnsafePointer<CChar>? @_inlineable // FIXME(sil-serialize-all) final public var hashValue: Int { var hash = 0 withBuffer { var buffer = $0 while true { let (component, type) = buffer.next() hash ^= _mixInt(component.value.hashValue) if let type = type { hash ^= _mixInt(unsafeBitCast(type, to: Int.self)) } else { break } } } return hash } @_inlineable // FIXME(sil-serialize-all) public static func ==(a: AnyKeyPath, b: AnyKeyPath) -> Bool { // Fast-path identical objects if a === b { return true } // Short-circuit differently-typed key paths if type(of: a) != type(of: b) { return false } return a.withBuffer { var aBuffer = $0 return b.withBuffer { var bBuffer = $0 // Two equivalent key paths should have the same reference prefix if aBuffer.hasReferencePrefix != bBuffer.hasReferencePrefix { return false } while true { let (aComponent, aType) = aBuffer.next() let (bComponent, bType) = bBuffer.next() if aComponent.header.endOfReferencePrefix != bComponent.header.endOfReferencePrefix || aComponent.value != bComponent.value || aType != bType { return false } if aType == nil { return true } } } } } // SPI for the Foundation overlay to allow interop with KVC keypath-based // APIs. @_inlineable // FIXME(sil-serialize-all) public var _kvcKeyPathString: String? { guard let ptr = _kvcKeyPathStringPtr else { return nil } return String(validatingUTF8: ptr) } // MARK: Implementation details // Prevent normal initialization. We use tail allocation via // allocWithTailElems(). @_inlineable // FIXME(sil-serialize-all) @_versioned // FIXME(sil-serialize-all) internal init() { _sanityCheckFailure("use _create(...)") } @_inlineable // FIXME(sil-serialize-all) deinit {} // internal-with-availability @_inlineable // FIXME(sil-serialize-all) public class var _rootAndValueType: (root: Any.Type, value: Any.Type) { _abstract() } @_inlineable // FIXME(sil-serialize-all) public // @testable static func _create( capacityInBytes bytes: Int, initializedBy body: (UnsafeMutableRawBufferPointer) -> Void ) -> Self { _sanityCheck(bytes > 0 && bytes % 4 == 0, "capacity must be multiple of 4 bytes") let result = Builtin.allocWithTailElems_1(self, (bytes/4)._builtinWordValue, Int32.self) result._kvcKeyPathStringPtr = nil let base = UnsafeMutableRawPointer(Builtin.projectTailElems(result, Int32.self)) body(UnsafeMutableRawBufferPointer(start: base, count: bytes)) return result } @_inlineable // FIXME(sil-serialize-all) @_versioned // FIXME(sil-serialize-all) internal func withBuffer<T>(_ f: (KeyPathBuffer) throws -> T) rethrows -> T { defer { _fixLifetime(self) } let base = UnsafeRawPointer(Builtin.projectTailElems(self, Int32.self)) return try f(KeyPathBuffer(base: base)) } } /// A partially type-erased key path, from a concrete root type to any /// resulting value type. @_fixed_layout // FIXME(sil-serialize-all) public class PartialKeyPath<Root>: AnyKeyPath { } // MARK: Concrete implementations @_versioned // FIXME(sil-serialize-all) internal enum KeyPathKind { case readOnly, value, reference } /// A key path from a specific root type to a specific resulting value type. @_fixed_layout // FIXME(sil-serialize-all) public class KeyPath<Root, Value>: PartialKeyPath<Root> { public typealias _Root = Root public typealias _Value = Value @_inlineable // FIXME(sil-serialize-all) public final override class var _rootAndValueType: ( root: Any.Type, value: Any.Type ) { return (Root.self, Value.self) } // MARK: Implementation internal typealias Kind = KeyPathKind @_inlineable // FIXME(sil-serialize-all) @_versioned // FIXME(sil-serialize-all) internal class var kind: Kind { return .readOnly } @_inlineable // FIXME(sil-serialize-all) @_versioned // FIXME(sil-serialize-all) internal static func appendedType<AppendedValue>( with t: KeyPath<Value, AppendedValue>.Type ) -> KeyPath<Root, AppendedValue>.Type { let resultKind: Kind switch (self.kind, t.kind) { case (_, .reference): resultKind = .reference case (let x, .value): resultKind = x default: resultKind = .readOnly } switch resultKind { case .readOnly: return KeyPath<Root, AppendedValue>.self case .value: return WritableKeyPath.self case .reference: return ReferenceWritableKeyPath.self } } @_inlineable // FIXME(sil-serialize-all) @_versioned // FIXME(sil-serialize-all) internal final func projectReadOnly(from root: Root) -> Value { // TODO: For perf, we could use a local growable buffer instead of Any var curBase: Any = root return withBuffer { var buffer = $0 while true { let (rawComponent, optNextType) = buffer.next() let valueType = optNextType ?? Value.self let isLast = optNextType == nil func project<CurValue>(_ base: CurValue) -> Value? { func project2<NewValue>(_: NewValue.Type) -> Value? { switch rawComponent.projectReadOnly(base, to: NewValue.self, endingWith: Value.self) { case .continue(let newBase): if isLast { _sanityCheck(NewValue.self == Value.self, "key path does not terminate in correct type") return unsafeBitCast(newBase, to: Value.self) } else { curBase = newBase return nil } case .break(let result): return result } } return _openExistential(valueType, do: project2) } if let result = _openExistential(curBase, do: project) { return result } } } } @_inlineable // FIXME(sil-serialize-all) deinit { withBuffer { $0.destroy() } } } /// A key path that supports reading from and writing to the resulting value. @_fixed_layout // FIXME(sil-serialize-all) public class WritableKeyPath<Root, Value>: KeyPath<Root, Value> { // MARK: Implementation detail @_inlineable // FIXME(sil-serialize-all) @_versioned // FIXME(sil-serialize-all) internal override class var kind: Kind { return .value } // `base` is assumed to be undergoing a formal access for the duration of the // call, so must not be mutated by an alias @_inlineable // FIXME(sil-serialize-all) @_versioned // FIXME(sil-serialize-all) internal func projectMutableAddress(from base: UnsafePointer<Root>) -> (pointer: UnsafeMutablePointer<Value>, owner: AnyObject?) { var p = UnsafeRawPointer(base) var type: Any.Type = Root.self var keepAlive: AnyObject? return withBuffer { var buffer = $0 _sanityCheck(!buffer.hasReferencePrefix, "WritableKeyPath should not have a reference prefix") while true { let (rawComponent, optNextType) = buffer.next() let nextType = optNextType ?? Value.self func project<CurValue>(_: CurValue.Type) { func project2<NewValue>(_: NewValue.Type) { p = rawComponent.projectMutableAddress(p, from: CurValue.self, to: NewValue.self, isRoot: p == UnsafeRawPointer(base), keepAlive: &keepAlive) } _openExistential(nextType, do: project2) } _openExistential(type, do: project) if optNextType == nil { break } type = nextType } // TODO: With coroutines, it would be better to yield here, so that // we don't need the hack of the keepAlive reference to manage closing // accesses. let typedPointer = p.assumingMemoryBound(to: Value.self) return (pointer: UnsafeMutablePointer(mutating: typedPointer), owner: keepAlive) } } } /// A key path that supports reading from and writing to the resulting value /// with reference semantics. @_fixed_layout // FIXME(sil-serialize-all) public class ReferenceWritableKeyPath< Root, Value > : WritableKeyPath<Root, Value> { // MARK: Implementation detail @_inlineable // FIXME(sil-serialize-all) @_versioned // FIXME(sil-serialize-all) internal final override class var kind: Kind { return .reference } @_inlineable // FIXME(sil-serialize-all) @_versioned // FIXME(sil-serialize-all) internal final override func projectMutableAddress( from base: UnsafePointer<Root> ) -> (pointer: UnsafeMutablePointer<Value>, owner: AnyObject?) { // Since we're a ReferenceWritableKeyPath, we know we don't mutate the base // in practice. return projectMutableAddress(from: base.pointee) } @_inlineable // FIXME(sil-serialize-all) @_versioned // FIXME(sil-serialize-all) internal final func projectMutableAddress(from origBase: Root) -> (pointer: UnsafeMutablePointer<Value>, owner: AnyObject?) { var keepAlive: AnyObject? var address: UnsafeMutablePointer<Value> = withBuffer { var buffer = $0 // Project out the reference prefix. var base: Any = origBase while buffer.hasReferencePrefix { let (rawComponent, optNextType) = buffer.next() _sanityCheck(optNextType != nil, "reference prefix should not go to end of buffer") let nextType = optNextType.unsafelyUnwrapped func project<NewValue>(_: NewValue.Type) -> Any { func project2<CurValue>(_ base: CurValue) -> Any { return rawComponent.projectReadOnly( base, to: NewValue.self, endingWith: Value.self) .assumingContinue } return _openExistential(base, do: project2) } base = _openExistential(nextType, do: project) } // Start formal access to the mutable value, based on the final base // value. func formalMutation<MutationRoot>(_ base: MutationRoot) -> UnsafeMutablePointer<Value> { var base2 = base return withUnsafeBytes(of: &base2) { baseBytes in var p = baseBytes.baseAddress.unsafelyUnwrapped var curType: Any.Type = MutationRoot.self while true { let (rawComponent, optNextType) = buffer.next() let nextType = optNextType ?? Value.self func project<CurValue>(_: CurValue.Type) { func project2<NewValue>(_: NewValue.Type) { p = rawComponent.projectMutableAddress(p, from: CurValue.self, to: NewValue.self, isRoot: p == baseBytes.baseAddress, keepAlive: &keepAlive) } _openExistential(nextType, do: project2) } _openExistential(curType, do: project) if optNextType == nil { break } curType = nextType } let typedPointer = p.assumingMemoryBound(to: Value.self) return UnsafeMutablePointer(mutating: typedPointer) } } return _openExistential(base, do: formalMutation) } return (address, keepAlive) } } // MARK: Implementation details @_versioned // FIXME(sil-serialize-all) internal enum KeyPathComponentKind { /// The keypath projects within the storage of the outer value, like a /// stored property in a struct. case `struct` /// The keypath projects from the referenced pointer, like a /// stored property in a class. case `class` /// The keypath projects using a getter/setter pair. case computed /// The keypath optional-chains, returning nil immediately if the input is /// nil, or else proceeding by projecting the value inside. case optionalChain /// The keypath optional-forces, trapping if the input is /// nil, or else proceeding by projecting the value inside. case optionalForce /// The keypath wraps a value in an optional. case optionalWrap } @_fixed_layout // FIXME(sil-serialize-all) @_versioned // FIXME(sil-serialize-all) internal struct ComputedPropertyID: Hashable { @_inlineable // FIXME(sil-serialize-all) @_versioned // FIXME(sil-serialize-all) internal init(value: Int, isStoredProperty: Bool, isTableOffset: Bool) { self.value = value self.isStoredProperty = isStoredProperty self.isTableOffset = isTableOffset } @_versioned // FIXME(sil-serialize-all) internal var value: Int @_versioned // FIXME(sil-serialize-all) internal var isStoredProperty: Bool @_versioned // FIXME(sil-serialize-all) internal var isTableOffset: Bool @_inlineable // FIXME(sil-serialize-all) @_versioned // FIXME(sil-serialize-all) internal static func ==( x: ComputedPropertyID, y: ComputedPropertyID ) -> Bool { return x.value == y.value && x.isStoredProperty == y.isStoredProperty && x.isTableOffset == x.isTableOffset } @_inlineable // FIXME(sil-serialize-all) @_versioned // FIXME(sil-serialize-all) internal var hashValue: Int { var hash = 0 hash ^= _mixInt(value) hash ^= _mixInt(isStoredProperty ? 13 : 17) hash ^= _mixInt(isTableOffset ? 19 : 23) return hash } } @_versioned // FIXME(sil-serialize-all) internal struct ComputedArgumentWitnesses { internal typealias Destroy = @convention(thin) (_ instanceArguments: UnsafeMutableRawPointer, _ size: Int) -> () internal typealias Copy = @convention(thin) (_ srcInstanceArguments: UnsafeRawPointer, _ destInstanceArguments: UnsafeMutableRawPointer, _ size: Int) -> () internal typealias Equals = @convention(thin) (_ xInstanceArguments: UnsafeRawPointer, _ yInstanceArguments: UnsafeRawPointer, _ size: Int) -> Bool internal typealias Hash = @convention(thin) (_ instanceArguments: UnsafeRawPointer, _ size: Int) -> Int @_versioned // FIXME(sil-serialize-all) internal let destroy: Destroy? @_versioned // FIXME(sil-serialize-all) internal let copy: Copy @_versioned // FIXME(sil-serialize-all) internal let equals: Equals @_versioned // FIXME(sil-serialize-all) internal let hash: Hash } @_versioned // FIXME(sil-serialize-all) internal enum KeyPathComponent: Hashable { @_fixed_layout // FIXME(sil-serialize-all) @_versioned // FIXME(sil-serialize-all) internal struct ArgumentRef { @_inlineable // FIXME(sil-serialize-all) @_versioned // FIXME(sil-serialize-all) internal init( data: UnsafeRawBufferPointer, witnesses: UnsafePointer<ComputedArgumentWitnesses> ) { self.data = data self.witnesses = witnesses } @_versioned // FIXME(sil-serialize-all) internal var data: UnsafeRawBufferPointer @_versioned // FIXME(sil-serialize-all) internal var witnesses: UnsafePointer<ComputedArgumentWitnesses> } /// The keypath projects within the storage of the outer value, like a /// stored property in a struct. case `struct`(offset: Int) /// The keypath projects from the referenced pointer, like a /// stored property in a class. case `class`(offset: Int) /// The keypath projects using a getter. case get(id: ComputedPropertyID, get: UnsafeRawPointer, argument: ArgumentRef?) /// The keypath projects using a getter/setter pair. The setter can mutate /// the base value in-place. case mutatingGetSet(id: ComputedPropertyID, get: UnsafeRawPointer, set: UnsafeRawPointer, argument: ArgumentRef?) /// The keypath projects using a getter/setter pair that does not mutate its /// base. case nonmutatingGetSet(id: ComputedPropertyID, get: UnsafeRawPointer, set: UnsafeRawPointer, argument: ArgumentRef?) /// The keypath optional-chains, returning nil immediately if the input is /// nil, or else proceeding by projecting the value inside. case optionalChain /// The keypath optional-forces, trapping if the input is /// nil, or else proceeding by projecting the value inside. case optionalForce /// The keypath wraps a value in an optional. case optionalWrap @_inlineable // FIXME(sil-serialize-all) @_versioned // FIXME(sil-serialize-all) internal static func ==(a: KeyPathComponent, b: KeyPathComponent) -> Bool { switch (a, b) { case (.struct(offset: let a), .struct(offset: let b)), (.class (offset: let a), .class (offset: let b)): return a == b case (.optionalChain, .optionalChain), (.optionalForce, .optionalForce), (.optionalWrap, .optionalWrap): return true case (.get(id: let id1, get: _, argument: let argument1), .get(id: let id2, get: _, argument: let argument2)), (.mutatingGetSet(id: let id1, get: _, set: _, argument: let argument1), .mutatingGetSet(id: let id2, get: _, set: _, argument: let argument2)), (.nonmutatingGetSet(id: let id1, get: _, set: _, argument: let argument1), .nonmutatingGetSet(id: let id2, get: _, set: _, argument: let argument2)): if id1 != id2 { return false } if let arg1 = argument1, let arg2 = argument2 { return arg1.witnesses.pointee.equals( arg1.data.baseAddress.unsafelyUnwrapped, arg2.data.baseAddress.unsafelyUnwrapped, arg1.data.count) } // If only one component has arguments, that should indicate that the // only arguments in that component were generic captures and therefore // not affecting equality. return true case (.struct, _), (.class, _), (.optionalChain, _), (.optionalForce, _), (.optionalWrap, _), (.get, _), (.mutatingGetSet, _), (.nonmutatingGetSet, _): return false } } @_inlineable // FIXME(sil-serialize-all) @_versioned // FIXME(sil-serialize-all) internal var hashValue: Int { var hash: Int = 0 func mixHashFromArgument(_ argument: KeyPathComponent.ArgumentRef?) { if let argument = argument { let addedHash = argument.witnesses.pointee.hash( argument.data.baseAddress.unsafelyUnwrapped, argument.data.count) // Returning 0 indicates that the arguments should not impact the // hash value of the overall key path. if addedHash != 0 { hash ^= _mixInt(addedHash) } } } switch self { case .struct(offset: let a): hash ^= _mixInt(0) hash ^= _mixInt(a) case .class(offset: let b): hash ^= _mixInt(1) hash ^= _mixInt(b) case .optionalChain: hash ^= _mixInt(2) case .optionalForce: hash ^= _mixInt(3) case .optionalWrap: hash ^= _mixInt(4) case .get(id: let id, get: _, argument: let argument): hash ^= _mixInt(5) hash ^= _mixInt(id.hashValue) mixHashFromArgument(argument) case .mutatingGetSet(id: let id, get: _, set: _, argument: let argument): hash ^= _mixInt(6) hash ^= _mixInt(id.hashValue) mixHashFromArgument(argument) case .nonmutatingGetSet(id: let id, get: _, set: _, argument: let argument): hash ^= _mixInt(7) hash ^= _mixInt(id.hashValue) mixHashFromArgument(argument) } return hash } } // A class that maintains ownership of another object while a mutable projection // into it is underway. @_fixed_layout // FIXME(sil-serialize-all) @_versioned // FIXME(sil-serialize-all) internal final class ClassHolder { @_versioned // FIXME(sil-serialize-all) internal let previous: AnyObject? @_versioned // FIXME(sil-serialize-all) internal let instance: AnyObject @_inlineable // FIXME(sil-serialize-all) @_versioned // FIXME(sil-serialize-all) internal init(previous: AnyObject?, instance: AnyObject) { self.previous = previous self.instance = instance } @_inlineable // FIXME(sil-serialize-all) @_versioned // FIXME(sil-serialize-all) deinit {} } // A class that triggers writeback to a pointer when destroyed. @_fixed_layout // FIXME(sil-serialize-all) @_versioned // FIXME(sil-serialize-all) internal final class MutatingWritebackBuffer<CurValue, NewValue> { @_versioned // FIXME(sil-serialize-all) internal let previous: AnyObject? @_versioned // FIXME(sil-serialize-all) internal let base: UnsafeMutablePointer<CurValue> @_versioned // FIXME(sil-serialize-all) internal let set: @convention(thin) (NewValue, inout CurValue, UnsafeRawPointer, Int) -> () @_versioned // FIXME(sil-serialize-all) internal let argument: UnsafeRawPointer @_versioned // FIXME(sil-serialize-all) internal let argumentSize: Int @_versioned // FIXME(sil-serialize-all) internal var value: NewValue @_inlineable // FIXME(sil-serialize-all) @_versioned // FIXME(sil-serialize-all) deinit { set(value, &base.pointee, argument, argumentSize) } @_inlineable // FIXME(sil-serialize-all) @_versioned // FIXME(sil-serialize-all) internal init(previous: AnyObject?, base: UnsafeMutablePointer<CurValue>, set: @escaping @convention(thin) (NewValue, inout CurValue, UnsafeRawPointer, Int) -> (), argument: UnsafeRawPointer, argumentSize: Int, value: NewValue) { self.previous = previous self.base = base self.set = set self.argument = argument self.argumentSize = argumentSize self.value = value } } // A class that triggers writeback to a non-mutated value when destroyed. @_fixed_layout // FIXME(sil-serialize-all) @_versioned // FIXME(sil-serialize-all) internal final class NonmutatingWritebackBuffer<CurValue, NewValue> { @_versioned // FIXME(sil-serialize-all) internal let previous: AnyObject? @_versioned // FIXME(sil-serialize-all) internal let base: CurValue @_versioned // FIXME(sil-serialize-all) internal let set: @convention(thin) (NewValue, CurValue, UnsafeRawPointer, Int) -> () @_versioned // FIXME(sil-serialize-all) internal let argument: UnsafeRawPointer @_versioned // FIXME(sil-serialize-all) internal let argumentSize: Int @_versioned // FIXME(sil-serialize-all) internal var value: NewValue @_inlineable // FIXME(sil-serialize-all) @_versioned // FIXME(sil-serialize-all) deinit { set(value, base, argument, argumentSize) } @_inlineable // FIXME(sil-serialize-all) @_versioned // FIXME(sil-serialize-all) internal init(previous: AnyObject?, base: CurValue, set: @escaping @convention(thin) (NewValue, CurValue, UnsafeRawPointer, Int) -> (), argument: UnsafeRawPointer, argumentSize: Int, value: NewValue) { self.previous = previous self.base = base self.set = set self.argument = argument self.argumentSize = argumentSize self.value = value } } @_fixed_layout // FIXME(sil-serialize-all) @_versioned // FIXME(sil-serialize-all) internal struct RawKeyPathComponent { @_inlineable // FIXME(sil-serialize-all) @_versioned // FIXME(sil-serialize-all) internal init(header: Header, body: UnsafeRawBufferPointer) { self.header = header self.body = body } @_versioned // FIXME(sil-serialize-all) internal var header: Header @_versioned // FIXME(sil-serialize-all) internal var body: UnsafeRawBufferPointer @_versioned // FIXME(sil-serialize-all) internal struct Header { @_inlineable // FIXME(sil-serialize-all) @_versioned // FIXME(sil-serialize-all) internal static var payloadMask: UInt32 { return _SwiftKeyPathComponentHeader_PayloadMask } @_inlineable // FIXME(sil-serialize-all) @_versioned // FIXME(sil-serialize-all) internal static var discriminatorMask: UInt32 { return _SwiftKeyPathComponentHeader_DiscriminatorMask } @_inlineable // FIXME(sil-serialize-all) @_versioned // FIXME(sil-serialize-all) internal static var discriminatorShift: UInt32 { return _SwiftKeyPathComponentHeader_DiscriminatorShift } @_inlineable // FIXME(sil-serialize-all) @_versioned // FIXME(sil-serialize-all) internal static var structTag: UInt32 { return _SwiftKeyPathComponentHeader_StructTag } @_inlineable // FIXME(sil-serialize-all) @_versioned // FIXME(sil-serialize-all) internal static var computedTag: UInt32 { return _SwiftKeyPathComponentHeader_ComputedTag } @_inlineable // FIXME(sil-serialize-all) @_versioned // FIXME(sil-serialize-all) internal static var classTag: UInt32 { return _SwiftKeyPathComponentHeader_ClassTag } @_inlineable // FIXME(sil-serialize-all) @_versioned // FIXME(sil-serialize-all) internal static var optionalTag: UInt32 { return _SwiftKeyPathComponentHeader_OptionalTag } @_inlineable // FIXME(sil-serialize-all) @_versioned // FIXME(sil-serialize-all) internal static var optionalChainPayload: UInt32 { return _SwiftKeyPathComponentHeader_OptionalChainPayload } @_inlineable // FIXME(sil-serialize-all) @_versioned // FIXME(sil-serialize-all) internal static var optionalWrapPayload: UInt32 { return _SwiftKeyPathComponentHeader_OptionalWrapPayload } @_inlineable // FIXME(sil-serialize-all) @_versioned // FIXME(sil-serialize-all) internal static var optionalForcePayload: UInt32 { return _SwiftKeyPathComponentHeader_OptionalForcePayload } @_inlineable // FIXME(sil-serialize-all) @_versioned // FIXME(sil-serialize-all) internal static var endOfReferencePrefixFlag: UInt32 { return _SwiftKeyPathComponentHeader_EndOfReferencePrefixFlag } @_inlineable // FIXME(sil-serialize-all) @_versioned // FIXME(sil-serialize-all) internal static var outOfLineOffsetPayload: UInt32 { return _SwiftKeyPathComponentHeader_OutOfLineOffsetPayload } @_inlineable // FIXME(sil-serialize-all) @_versioned // FIXME(sil-serialize-all) internal static var unresolvedFieldOffsetPayload: UInt32 { return _SwiftKeyPathComponentHeader_UnresolvedFieldOffsetPayload } @_inlineable // FIXME(sil-serialize-all) @_versioned // FIXME(sil-serialize-all) internal static var unresolvedIndirectOffsetPayload: UInt32 { return _SwiftKeyPathComponentHeader_UnresolvedIndirectOffsetPayload } @_inlineable // FIXME(sil-serialize-all) @_versioned // FIXME(sil-serialize-all) internal static var computedMutatingFlag: UInt32 { return _SwiftKeyPathComponentHeader_ComputedMutatingFlag } @_inlineable // FIXME(sil-serialize-all) @_versioned // FIXME(sil-serialize-all) internal static var computedSettableFlag: UInt32 { return _SwiftKeyPathComponentHeader_ComputedSettableFlag } @_inlineable // FIXME(sil-serialize-all) @_versioned // FIXME(sil-serialize-all) internal static var computedIDByStoredPropertyFlag: UInt32 { return _SwiftKeyPathComponentHeader_ComputedIDByStoredPropertyFlag } @_inlineable // FIXME(sil-serialize-all) @_versioned // FIXME(sil-serialize-all) internal static var computedIDByVTableOffsetFlag: UInt32 { return _SwiftKeyPathComponentHeader_ComputedIDByVTableOffsetFlag } @_inlineable // FIXME(sil-serialize-all) @_versioned // FIXME(sil-serialize-all) internal static var computedHasArgumentsFlag: UInt32 { return _SwiftKeyPathComponentHeader_ComputedHasArgumentsFlag } @_inlineable // FIXME(sil-serialize-all) @_versioned // FIXME(sil-serialize-all) internal static var computedIDResolutionMask: UInt32 { return _SwiftKeyPathComponentHeader_ComputedIDResolutionMask } @_inlineable // FIXME(sil-serialize-all) @_versioned // FIXME(sil-serialize-all) internal static var computedIDResolved: UInt32 { return _SwiftKeyPathComponentHeader_ComputedIDResolved } @_inlineable // FIXME(sil-serialize-all) @_versioned // FIXME(sil-serialize-all) internal static var computedIDUnresolvedIndirectPointer: UInt32 { return _SwiftKeyPathComponentHeader_ComputedIDUnresolvedIndirectPointer } @_versioned // FIXME(sil-serialize-all) internal var _value: UInt32 @_inlineable // FIXME(sil-serialize-all) @_versioned // FIXME(sil-serialize-all) internal var discriminator: UInt32 { return (_value & Header.discriminatorMask) >> Header.discriminatorShift } @_inlineable // FIXME(sil-serialize-all) @_versioned // FIXME(sil-serialize-all) internal var payload: UInt32 { get { return _value & Header.payloadMask } set { _sanityCheck(newValue & Header.payloadMask == newValue, "payload too big") _value = _value & ~Header.payloadMask | newValue } } @_inlineable // FIXME(sil-serialize-all) @_versioned // FIXME(sil-serialize-all) internal var endOfReferencePrefix: Bool { get { return _value & Header.endOfReferencePrefixFlag != 0 } set { if newValue { _value |= Header.endOfReferencePrefixFlag } else { _value &= ~Header.endOfReferencePrefixFlag } } } @_inlineable // FIXME(sil-serialize-all) @_versioned // FIXME(sil-serialize-all) internal var kind: KeyPathComponentKind { switch (discriminator, payload) { case (Header.structTag, _): return .struct case (Header.classTag, _): return .class case (Header.computedTag, _): return .computed case (Header.optionalTag, Header.optionalChainPayload): return .optionalChain case (Header.optionalTag, Header.optionalWrapPayload): return .optionalWrap case (Header.optionalTag, Header.optionalForcePayload): return .optionalForce default: _sanityCheckFailure("invalid header") } } // The component header is 4 bytes, but may be followed by an aligned // pointer field for some kinds of component, forcing padding. @_inlineable // FIXME(sil-serialize-all) @_versioned // FIXME(sil-serialize-all) internal static var pointerAlignmentSkew: Int { return MemoryLayout<Int>.size - MemoryLayout<Int32>.size } } @_inlineable // FIXME(sil-serialize-all) @_versioned // FIXME(sil-serialize-all) internal var bodySize: Int { switch header.kind { case .struct, .class: if header.payload == Header.payloadMask { return 4 } // overflowed return 0 case .optionalChain, .optionalForce, .optionalWrap: return 0 case .computed: let ptrSize = MemoryLayout<Int>.size // align to pointer, minimum two pointers for id and get var total = Header.pointerAlignmentSkew + ptrSize * 2 // additional word for a setter if header.payload & Header.computedSettableFlag != 0 { total += ptrSize } // include the argument size if header.payload & Header.computedHasArgumentsFlag != 0 { // two words for argument header: size, witnesses total += ptrSize * 2 // size of argument area total += _computedArgumentSize } return total } } @_inlineable // FIXME(sil-serialize-all) @_versioned // FIXME(sil-serialize-all) internal var _structOrClassOffset: Int { _sanityCheck(header.kind == .struct || header.kind == .class, "no offset for this kind") // An offset too large to fit inline is represented by a signal and stored // in the body. if header.payload == Header.outOfLineOffsetPayload { // Offset overflowed into body _sanityCheck(body.count >= MemoryLayout<UInt32>.size, "component not big enough") return Int(body.load(as: UInt32.self)) } return Int(header.payload) } @_inlineable // FIXME(sil-serialize-all) @_versioned // FIXME(sil-serialize-all) internal var _computedIDValue: Int { _sanityCheck(header.kind == .computed, "not a computed property") return body.load(fromByteOffset: Header.pointerAlignmentSkew, as: Int.self) } @_inlineable // FIXME(sil-serialize-all) @_versioned // FIXME(sil-serialize-all) internal var _computedID: ComputedPropertyID { let payload = header.payload return ComputedPropertyID( value: _computedIDValue, isStoredProperty: payload & Header.computedIDByStoredPropertyFlag != 0, isTableOffset: payload & Header.computedIDByVTableOffsetFlag != 0) } @_inlineable // FIXME(sil-serialize-all) @_versioned // FIXME(sil-serialize-all) internal var _computedGetter: UnsafeRawPointer { _sanityCheck(header.kind == .computed, "not a computed property") return body.load( fromByteOffset: Header.pointerAlignmentSkew + MemoryLayout<Int>.size, as: UnsafeRawPointer.self) } @_inlineable // FIXME(sil-serialize-all) @_versioned // FIXME(sil-serialize-all) internal var _computedSetter: UnsafeRawPointer { _sanityCheck(header.kind == .computed, "not a computed property") _sanityCheck(header.payload & Header.computedSettableFlag != 0, "not a settable property") return body.load( fromByteOffset: Header.pointerAlignmentSkew + MemoryLayout<Int>.size * 2, as: UnsafeRawPointer.self) } internal typealias ComputedArgumentLayoutFn = @convention(thin) (_ patternArguments: UnsafeRawPointer) -> (size: Int, alignmentMask: Int) internal typealias ComputedArgumentInitializerFn = @convention(thin) (_ patternArguments: UnsafeRawPointer, _ instanceArguments: UnsafeMutableRawPointer) -> () @_inlineable // FIXME(sil-serialize-all) @_versioned // FIXME(sil-serialize-all) internal var _computedArgumentHeaderPointer: UnsafeRawPointer { _sanityCheck(header.kind == .computed, "not a computed property") _sanityCheck(header.payload & Header.computedHasArgumentsFlag != 0, "no arguments") return body.baseAddress.unsafelyUnwrapped + Header.pointerAlignmentSkew + MemoryLayout<Int>.size * (header.payload & Header.computedSettableFlag != 0 ? 3 : 2) } @_inlineable // FIXME(sil-serialize-all) @_versioned // FIXME(sil-serialize-all) internal var _computedArgumentSize: Int { return _computedArgumentHeaderPointer.load(as: Int.self) } @_inlineable // FIXME(sil-serialize-all) @_versioned // FIXME(sil-serialize-all) internal var _computedArgumentWitnesses: UnsafePointer<ComputedArgumentWitnesses> { return _computedArgumentHeaderPointer.load( fromByteOffset: MemoryLayout<Int>.size, as: UnsafePointer<ComputedArgumentWitnesses>.self) } @_inlineable // FIXME(sil-serialize-all) @_versioned // FIXME(sil-serialize-all) internal var _computedArguments: UnsafeRawPointer { return _computedArgumentHeaderPointer + MemoryLayout<Int>.size * 2 } @_inlineable // FIXME(sil-serialize-all) @_versioned // FIXME(sil-serialize-all) internal var _computedMutableArguments: UnsafeMutableRawPointer { return UnsafeMutableRawPointer(mutating: _computedArguments) } @_inlineable // FIXME(sil-serialize-all) @_versioned // FIXME(sil-serialize-all) internal var value: KeyPathComponent { switch header.kind { case .struct: return .struct(offset: _structOrClassOffset) case .class: return .class(offset: _structOrClassOffset) case .optionalChain: return .optionalChain case .optionalForce: return .optionalForce case .optionalWrap: return .optionalWrap case .computed: let isSettable = header.payload & Header.computedSettableFlag != 0 let isMutating = header.payload & Header.computedMutatingFlag != 0 let id = _computedID let get = _computedGetter // Argument value is unused if there are no arguments, so pick something // likely to already be in a register as a default. let argument: KeyPathComponent.ArgumentRef? if header.payload & Header.computedHasArgumentsFlag != 0 { argument = KeyPathComponent.ArgumentRef( data: UnsafeRawBufferPointer(start: _computedArguments, count: _computedArgumentSize), witnesses: _computedArgumentWitnesses) } else { argument = nil } switch (isSettable, isMutating) { case (false, false): return .get(id: id, get: get, argument: argument) case (true, false): return .nonmutatingGetSet(id: id, get: get, set: _computedSetter, argument: argument) case (true, true): return .mutatingGetSet(id: id, get: get, set: _computedSetter, argument: argument) case (false, true): _sanityCheckFailure("impossible") } } } @_inlineable // FIXME(sil-serialize-all) @_versioned // FIXME(sil-serialize-all) internal func destroy() { switch header.kind { case .struct, .class, .optionalChain, .optionalForce, .optionalWrap: // trivial break case .computed: // Run destructor, if any if header.payload & Header.computedHasArgumentsFlag != 0, let destructor = _computedArgumentWitnesses.pointee.destroy { destructor(_computedMutableArguments, _computedArgumentSize) } } } @_inlineable // FIXME(sil-serialize-all) @_versioned // FIXME(sil-serialize-all) internal func clone(into buffer: inout UnsafeMutableRawBufferPointer, endOfReferencePrefix: Bool) { var newHeader = header newHeader.endOfReferencePrefix = endOfReferencePrefix var componentSize = MemoryLayout<Header>.size buffer.storeBytes(of: newHeader, as: Header.self) switch header.kind { case .struct, .class: if header.payload == Header.outOfLineOffsetPayload { let overflowOffset = body.load(as: UInt32.self) buffer.storeBytes(of: overflowOffset, toByteOffset: 4, as: UInt32.self) componentSize += 4 } case .optionalChain, .optionalForce, .optionalWrap: break case .computed: // Fields are pointer-aligned after the header componentSize += Header.pointerAlignmentSkew buffer.storeBytes(of: _computedIDValue, toByteOffset: MemoryLayout<Int>.size, as: Int.self) buffer.storeBytes(of: _computedGetter, toByteOffset: 2 * MemoryLayout<Int>.size, as: UnsafeRawPointer.self) var addedSize = MemoryLayout<Int>.size * 2 if header.payload & Header.computedSettableFlag != 0 { buffer.storeBytes(of: _computedSetter, toByteOffset: MemoryLayout<Int>.size * 3, as: UnsafeRawPointer.self) addedSize += MemoryLayout<Int>.size } if header.payload & Header.computedHasArgumentsFlag != 0 { let argumentSize = _computedArgumentSize buffer.storeBytes(of: argumentSize, toByteOffset: addedSize + MemoryLayout<Int>.size, as: Int.self) buffer.storeBytes(of: _computedArgumentWitnesses, toByteOffset: addedSize + MemoryLayout<Int>.size * 2, as: UnsafePointer<ComputedArgumentWitnesses>.self) _computedArgumentWitnesses.pointee.copy( _computedArguments, buffer.baseAddress.unsafelyUnwrapped + addedSize + MemoryLayout<Int>.size * 3, argumentSize) addedSize += MemoryLayout<Int>.size * 2 + argumentSize } componentSize += addedSize } buffer = UnsafeMutableRawBufferPointer( start: buffer.baseAddress.unsafelyUnwrapped + componentSize, count: buffer.count - componentSize) } @_versioned // FIXME(sil-serialize-all) internal enum ProjectionResult<NewValue, LeafValue> { /// Continue projecting the key path with the given new value. case `continue`(NewValue) /// Stop projecting the key path and use the given value as the final /// result of the projection. case `break`(LeafValue) @_inlineable // FIXME(sil-serialize-all) @_versioned // FIXME(sil-serialize-all) internal var assumingContinue: NewValue { switch self { case .continue(let x): return x case .break: _sanityCheckFailure("should not have stopped key path projection") } } } @_inlineable // FIXME(sil-serialize-all) @_versioned // FIXME(sil-serialize-all) internal func projectReadOnly<CurValue, NewValue, LeafValue>( _ base: CurValue, to: NewValue.Type, endingWith: LeafValue.Type ) -> ProjectionResult<NewValue, LeafValue> { switch value { case .struct(let offset): var base2 = base return .continue(withUnsafeBytes(of: &base2) { let p = $0.baseAddress.unsafelyUnwrapped.advanced(by: offset) // The contents of the struct should be well-typed, so we can assume // typed memory here. return p.assumingMemoryBound(to: NewValue.self).pointee }) case .class(let offset): _sanityCheck(CurValue.self is AnyObject.Type, "base is not a class") let baseObj = unsafeBitCast(base, to: AnyObject.self) let basePtr = UnsafeRawPointer(Builtin.bridgeToRawPointer(baseObj)) defer { _fixLifetime(baseObj) } return .continue(basePtr.advanced(by: offset) .assumingMemoryBound(to: NewValue.self) .pointee) case .get(id: _, get: let rawGet, argument: let argument), .mutatingGetSet(id: _, get: let rawGet, set: _, argument: let argument), .nonmutatingGetSet(id: _, get: let rawGet, set: _, argument: let argument): typealias Getter = @convention(thin) (CurValue, UnsafeRawPointer, Int) -> NewValue let get = unsafeBitCast(rawGet, to: Getter.self) return .continue(get(base, argument?.data.baseAddress ?? rawGet, argument?.data.count ?? 0)) case .optionalChain: // TODO: IUO shouldn't be a first class type _sanityCheck(CurValue.self == Optional<NewValue>.self || CurValue.self == ImplicitlyUnwrappedOptional<NewValue>.self, "should be unwrapping optional value") _sanityCheck(_isOptional(LeafValue.self), "leaf result should be optional") if let baseValue = unsafeBitCast(base, to: Optional<NewValue>.self) { return .continue(baseValue) } else { // TODO: A more efficient way of getting the `none` representation // of a dynamically-optional type... return .break((Optional<()>.none as Any) as! LeafValue) } case .optionalForce: // TODO: IUO shouldn't be a first class type _sanityCheck(CurValue.self == Optional<NewValue>.self || CurValue.self == ImplicitlyUnwrappedOptional<NewValue>.self, "should be unwrapping optional value") return .continue(unsafeBitCast(base, to: Optional<NewValue>.self)!) case .optionalWrap: // TODO: IUO shouldn't be a first class type _sanityCheck(NewValue.self == Optional<CurValue>.self || CurValue.self == ImplicitlyUnwrappedOptional<CurValue>.self, "should be wrapping optional value") return .continue( unsafeBitCast(base as Optional<CurValue>, to: NewValue.self)) } } @_inlineable // FIXME(sil-serialize-all) @_versioned // FIXME(sil-serialize-all) internal func projectMutableAddress<CurValue, NewValue>( _ base: UnsafeRawPointer, from _: CurValue.Type, to _: NewValue.Type, isRoot: Bool, keepAlive: inout AnyObject? ) -> UnsafeRawPointer { switch value { case .struct(let offset): return base.advanced(by: offset) case .class(let offset): // A class dereference should only occur at the root of a mutation, // since otherwise it would be part of the reference prefix. _sanityCheck(isRoot, "class component should not appear in the middle of mutation") // AnyObject memory can alias any class reference memory, so we can // assume type here let object = base.assumingMemoryBound(to: AnyObject.self).pointee // The base ought to be kept alive for the duration of the derived access keepAlive = keepAlive == nil ? object : ClassHolder(previous: keepAlive, instance: object) return UnsafeRawPointer(Builtin.bridgeToRawPointer(object)) .advanced(by: offset) case .mutatingGetSet(id: _, get: let rawGet, set: let rawSet, argument: let argument): typealias Getter = @convention(thin) (CurValue, UnsafeRawPointer, Int) -> NewValue typealias Setter = @convention(thin) (NewValue, inout CurValue, UnsafeRawPointer, Int) -> () let get = unsafeBitCast(rawGet, to: Getter.self) let set = unsafeBitCast(rawSet, to: Setter.self) let baseTyped = UnsafeMutablePointer( mutating: base.assumingMemoryBound(to: CurValue.self)) let argValue = argument?.data.baseAddress ?? rawGet let argSize = argument?.data.count ?? 0 let writeback = MutatingWritebackBuffer(previous: keepAlive, base: baseTyped, set: set, argument: argValue, argumentSize: argSize, value: get(baseTyped.pointee, argValue, argSize)) keepAlive = writeback // A maximally-abstracted, final, stored class property should have // a stable address. return UnsafeRawPointer(Builtin.addressof(&writeback.value)) case .nonmutatingGetSet(id: _, get: let rawGet, set: let rawSet, argument: let argument): // A nonmutating property should only occur at the root of a mutation, // since otherwise it would be part of the reference prefix. _sanityCheck(isRoot, "nonmutating component should not appear in the middle of mutation") typealias Getter = @convention(thin) (CurValue, UnsafeRawPointer, Int) -> NewValue typealias Setter = @convention(thin) (NewValue, CurValue, UnsafeRawPointer, Int) -> () let get = unsafeBitCast(rawGet, to: Getter.self) let set = unsafeBitCast(rawSet, to: Setter.self) let baseValue = base.assumingMemoryBound(to: CurValue.self).pointee let argValue = argument?.data.baseAddress ?? rawGet let argSize = argument?.data.count ?? 0 let writeback = NonmutatingWritebackBuffer(previous: keepAlive, base: baseValue, set: set, argument: argValue, argumentSize: argSize, value: get(baseValue, argValue, argSize)) keepAlive = writeback // A maximally-abstracted, final, stored class property should have // a stable address. return UnsafeRawPointer(Builtin.addressof(&writeback.value)) case .optionalForce: // TODO: ImplicitlyUnwrappedOptional should not be a first-class type _sanityCheck(CurValue.self == Optional<NewValue>.self || CurValue.self == ImplicitlyUnwrappedOptional<NewValue>.self, "should be unwrapping an optional value") // Optional's layout happens to always put the payload at the start // address of the Optional value itself, if a value is present at all. let baseOptionalPointer = base.assumingMemoryBound(to: Optional<NewValue>.self) // Assert that a value exists _ = baseOptionalPointer.pointee! return base case .optionalChain, .optionalWrap, .get: _sanityCheckFailure("not a mutable key path component") } } } @_fixed_layout // FIXME(sil-serialize-all) @_versioned // FIXME(sil-serialize-all) internal struct KeyPathBuffer { @_versioned // FIXME(sil-serialize-all) internal var data: UnsafeRawBufferPointer @_versioned // FIXME(sil-serialize-all) internal var trivial: Bool @_versioned // FIXME(sil-serialize-all) internal var hasReferencePrefix: Bool @_inlineable // FIXME(sil-serialize-all) @_versioned // FIXME(sil-serialize-all) internal var mutableData: UnsafeMutableRawBufferPointer { return UnsafeMutableRawBufferPointer(mutating: data) } @_fixed_layout // FIXME(sil-serialize-all) @_versioned // FIXME(sil-serialize-all) internal struct Header { @_versioned // FIXME(sil-serialize-all) internal var _value: UInt32 @_versioned // FIXME(sil-serialize-all) internal static var sizeMask: UInt32 { return _SwiftKeyPathBufferHeader_SizeMask } @_versioned // FIXME(sil-serialize-all) internal static var reservedMask: UInt32 { return _SwiftKeyPathBufferHeader_ReservedMask } @_versioned // FIXME(sil-serialize-all) internal static var trivialFlag: UInt32 { return _SwiftKeyPathBufferHeader_TrivialFlag } @_versioned // FIXME(sil-serialize-all) internal static var hasReferencePrefixFlag: UInt32 { return _SwiftKeyPathBufferHeader_HasReferencePrefixFlag } @_inlineable // FIXME(sil-serialize-all) @_versioned // FIXME(sil-serialize-all) internal init(size: Int, trivial: Bool, hasReferencePrefix: Bool) { _sanityCheck(size <= Int(Header.sizeMask), "key path too big") _value = UInt32(size) | (trivial ? Header.trivialFlag : 0) | (hasReferencePrefix ? Header.hasReferencePrefixFlag : 0) } @_inlineable // FIXME(sil-serialize-all) @_versioned // FIXME(sil-serialize-all) internal var size: Int { return Int(_value & Header.sizeMask) } @_inlineable // FIXME(sil-serialize-all) @_versioned // FIXME(sil-serialize-all) internal var trivial: Bool { return _value & Header.trivialFlag != 0 } @_inlineable // FIXME(sil-serialize-all) @_versioned // FIXME(sil-serialize-all) internal var hasReferencePrefix: Bool { get { return _value & Header.hasReferencePrefixFlag != 0 } set { if newValue { _value |= Header.hasReferencePrefixFlag } else { _value &= ~Header.hasReferencePrefixFlag } } } // In a key path pattern, the "trivial" flag is used to indicate // "instantiable in-line" @_inlineable // FIXME(sil-serialize-all) @_versioned // FIXME(sil-serialize-all) internal var instantiableInLine: Bool { return trivial } @_inlineable // FIXME(sil-serialize-all) @_versioned // FIXME(sil-serialize-all) internal func validateReservedBits() { _precondition(_value & Header.reservedMask == 0, "Reserved bits set to an unexpected bit pattern") } } @_inlineable // FIXME(sil-serialize-all) @_versioned // FIXME(sil-serialize-all) internal init(base: UnsafeRawPointer) { let header = base.load(as: Header.self) data = UnsafeRawBufferPointer( start: base + MemoryLayout<Int>.size, count: header.size) trivial = header.trivial hasReferencePrefix = header.hasReferencePrefix } @_inlineable // FIXME(sil-serialize-all) @_versioned // FIXME(sil-serialize-all) internal func destroy() { // Short-circuit if nothing in the object requires destruction. if trivial { return } var bufferToDestroy = self while true { let (component, type) = bufferToDestroy.next() component.destroy() guard let _ = type else { break } } } @_inlineable // FIXME(sil-serialize-all) @_versioned // FIXME(sil-serialize-all) internal mutating func next() -> (RawKeyPathComponent, Any.Type?) { let header = pop(RawKeyPathComponent.Header.self) // Track if this is the last component of the reference prefix. if header.endOfReferencePrefix { _sanityCheck(self.hasReferencePrefix, "beginMutation marker in non-reference-writable key path?") self.hasReferencePrefix = false } var component = RawKeyPathComponent(header: header, body: data) // Shrinkwrap the component buffer size. let size = component.bodySize component.body = UnsafeRawBufferPointer(start: component.body.baseAddress, count: size) _ = popRaw(size: size, alignment: 1) // fetch type, which is in the buffer unless it's the final component let nextType: Any.Type? if data.count == 0 { nextType = nil } else { nextType = pop(Any.Type.self) } return (component, nextType) } @_inlineable // FIXME(sil-serialize-all) @_versioned // FIXME(sil-serialize-all) internal mutating func pop<T>(_ type: T.Type) -> T { _sanityCheck(_isPOD(T.self), "should be POD") let raw = popRaw(size: MemoryLayout<T>.size, alignment: MemoryLayout<T>.alignment) let resultBuf = UnsafeMutablePointer<T>.allocate(capacity: 1) _memcpy(dest: resultBuf, src: UnsafeMutableRawPointer(mutating: raw.baseAddress.unsafelyUnwrapped), size: UInt(MemoryLayout<T>.size)) let result = resultBuf.pointee resultBuf.deallocate() return result } @_inlineable // FIXME(sil-serialize-all) @_versioned // FIXME(sil-serialize-all) internal mutating func popRaw(size: Int, alignment: Int) -> UnsafeRawBufferPointer { var baseAddress = data.baseAddress.unsafelyUnwrapped var misalignment = Int(bitPattern: baseAddress) % alignment if misalignment != 0 { misalignment = alignment - misalignment baseAddress += misalignment } let result = UnsafeRawBufferPointer(start: baseAddress, count: size) data = UnsafeRawBufferPointer( start: baseAddress + size, count: data.count - size - misalignment ) return result } } // MARK: Library intrinsics for projecting key paths. @_inlineable public // COMPILER_INTRINSIC func _projectKeyPathPartial<Root>( root: Root, keyPath: PartialKeyPath<Root> ) -> Any { func open<Value>(_: Value.Type) -> Any { return _projectKeyPathReadOnly(root: root, keyPath: unsafeDowncast(keyPath, to: KeyPath<Root, Value>.self)) } return _openExistential(type(of: keyPath).valueType, do: open) } @_inlineable public // COMPILER_INTRINSIC func _projectKeyPathAny<RootValue>( root: RootValue, keyPath: AnyKeyPath ) -> Any? { let (keyPathRoot, keyPathValue) = type(of: keyPath)._rootAndValueType func openRoot<KeyPathRoot>(_: KeyPathRoot.Type) -> Any? { guard let rootForKeyPath = root as? KeyPathRoot else { return nil } func openValue<Value>(_: Value.Type) -> Any { return _projectKeyPathReadOnly(root: rootForKeyPath, keyPath: unsafeDowncast(keyPath, to: KeyPath<KeyPathRoot, Value>.self)) } return _openExistential(keyPathValue, do: openValue) } return _openExistential(keyPathRoot, do: openRoot) } @_inlineable // FIXME(sil-serialize-all) public // COMPILER_INTRINSIC func _projectKeyPathReadOnly<Root, Value>( root: Root, keyPath: KeyPath<Root, Value> ) -> Value { return keyPath.projectReadOnly(from: root) } @_inlineable // FIXME(sil-serialize-all) public // COMPILER_INTRINSIC func _projectKeyPathWritable<Root, Value>( root: UnsafeMutablePointer<Root>, keyPath: WritableKeyPath<Root, Value> ) -> (UnsafeMutablePointer<Value>, AnyObject?) { return keyPath.projectMutableAddress(from: root) } @_inlineable // FIXME(sil-serialize-all) public // COMPILER_INTRINSIC func _projectKeyPathReferenceWritable<Root, Value>( root: Root, keyPath: ReferenceWritableKeyPath<Root, Value> ) -> (UnsafeMutablePointer<Value>, AnyObject?) { return keyPath.projectMutableAddress(from: root) } // MARK: Appending type system // FIXME(ABI): The type relationships between KeyPath append operands are tricky // and don't interact well with our overriding rules. Hack things by injecting // a bunch of `appending` overloads as protocol extensions so they aren't // constrained by being overrides, and so that we can use exact-type constraints // on `Self` to prevent dynamically-typed methods from being inherited by // statically-typed key paths. /// An implementation detail of key path expressions; do not use this protocol /// directly. @_show_in_interface public protocol _AppendKeyPath {} extension _AppendKeyPath where Self == AnyKeyPath { /// Returns a new key path created by appending the given key path to this /// one. /// /// Use this method to extend this key path to the value type of another key /// path. Appending the key path passed as `path` is successful only if the /// root type for `path` matches this key path's value type. This example /// creates key paths from `Array<Int>` to `String` and from `String` to /// `Int`, and then tries appending each to the other: /// /// let arrayDescription: AnyKeyPath = \Array<Int>.description /// let stringLength: AnyKeyPath = \String.count /// /// // Creates a key path from `Array<Int>` to `Int` /// let arrayDescriptionLength = arrayDescription.appending(path: stringLength) /// /// let invalidKeyPath = stringLength.appending(path: arrayDescription) /// // invalidKeyPath == nil /// /// The second call to `appending(path:)` returns `nil` /// because the root type of `arrayDescription`, `Array<Int>`, does not /// match the value type of `stringLength`, `Int`. /// /// - Parameter path: The key path to append. /// - Returns: A key path from the root of this key path and the value type /// of `path`, if `path` can be appended. If `path` can't be appended, /// returns `nil`. @_inlineable // FIXME(sil-serialize-all) public func appending(path: AnyKeyPath) -> AnyKeyPath? { return _tryToAppendKeyPaths(root: self, leaf: path) } } extension _AppendKeyPath /* where Self == PartialKeyPath<T> */ { /// Returns a new key path created by appending the given key path to this /// one. /// /// Use this method to extend this key path to the value type of another key /// path. Appending the key path passed as `path` is successful only if the /// root type for `path` matches this key path's value type. This example /// creates key paths from `Array<Int>` to `String` and from `String` to /// `Int`, and then tries appending each to the other: /// /// let arrayDescription: PartialKeyPath<Array<Int>> = \.description /// let stringLength: PartialKeyPath<String> = \.count /// /// // Creates a key path from `Array<Int>` to `Int` /// let arrayDescriptionLength = arrayDescription.appending(path: stringLength) /// /// let invalidKeyPath = stringLength.appending(path: arrayDescription) /// // invalidKeyPath == nil /// /// The second call to `appending(path:)` returns `nil` /// because the root type of `arrayDescription`, `Array<Int>`, does not /// match the value type of `stringLength`, `Int`. /// /// - Parameter path: The key path to append. /// - Returns: A key path from the root of this key path and the value type /// of `path`, if `path` can be appended. If `path` can't be appended, /// returns `nil`. @_inlineable // FIXME(sil-serialize-all) public func appending<Root>(path: AnyKeyPath) -> PartialKeyPath<Root>? where Self == PartialKeyPath<Root> { return _tryToAppendKeyPaths(root: self, leaf: path) } /// Returns a new key path created by appending the given key path to this /// one. /// /// Use this method to extend this key path to the value type of another key /// path. Appending the key path passed as `path` is successful only if the /// root type for `path` matches this key path's value type. This example /// creates a key path from `Array<Int>` to `String`, and then tries /// appending compatible and incompatible key paths: /// /// let arrayDescription: PartialKeyPath<Array<Int>> = \.description /// /// // Creates a key path from `Array<Int>` to `Int` /// let arrayDescriptionLength = arrayDescription.appending(path: \String.count) /// /// let invalidKeyPath = arrayDescription.appending(path: \Double.isZero) /// // invalidKeyPath == nil /// /// The second call to `appending(path:)` returns `nil` because the root type /// of the `path` parameter, `Double`, does not match the value type of /// `arrayDescription`, `String`. /// /// - Parameter path: The key path to append. /// - Returns: A key path from the root of this key path to the value type /// of `path`, if `path` can be appended. If `path` can't be appended, /// returns `nil`. @_inlineable // FIXME(sil-serialize-all) public func appending<Root, AppendedRoot, AppendedValue>( path: KeyPath<AppendedRoot, AppendedValue> ) -> KeyPath<Root, AppendedValue>? where Self == PartialKeyPath<Root> { return _tryToAppendKeyPaths(root: self, leaf: path) } /// Returns a new key path created by appending the given key path to this /// one. /// /// Use this method to extend this key path to the value type of another key /// path. Appending the key path passed as `path` is successful only if the /// root type for `path` matches this key path's value type. /// /// - Parameter path: The reference writeable key path to append. /// - Returns: A key path from the root of this key path to the value type /// of `path`, if `path` can be appended. If `path` can't be appended, /// returns `nil`. @_inlineable // FIXME(sil-serialize-all) public func appending<Root, AppendedRoot, AppendedValue>( path: ReferenceWritableKeyPath<AppendedRoot, AppendedValue> ) -> ReferenceWritableKeyPath<Root, AppendedValue>? where Self == PartialKeyPath<Root> { return _tryToAppendKeyPaths(root: self, leaf: path) } } extension _AppendKeyPath /* where Self == KeyPath<T,U> */ { /// Returns a new key path created by appending the given key path to this /// one. /// /// Use this method to extend this key path to the value type of another key /// path. Calling `appending(path:)` results in the same key path as if the /// given key path had been specified using dot notation. In the following /// example, `keyPath1` and `keyPath2` are equivalent: /// /// let arrayDescription = \Array<Int>.description /// let keyPath1 = arrayDescription.appending(path: \String.count) /// /// let keyPath2 = \Array<Int>.description.count /// /// - Parameter path: The key path to append. /// - Returns: A key path from the root of this key path to the value type of /// `path`. @_inlineable // FIXME(sil-serialize-all) public func appending<Root, Value, AppendedValue>( path: KeyPath<Value, AppendedValue> ) -> KeyPath<Root, AppendedValue> where Self: KeyPath<Root, Value> { return _appendingKeyPaths(root: self, leaf: path) } /* TODO public func appending<Root, Value, Leaf>( path: Leaf, // FIXME: Satisfy "Value generic param not used in signature" constraint _: Value.Type = Value.self ) -> PartialKeyPath<Root>? where Self: KeyPath<Root, Value>, Leaf == AnyKeyPath { return _tryToAppendKeyPaths(root: self, leaf: path) } */ /// Returns a new key path created by appending the given key path to this /// one. /// /// Use this method to extend this key path to the value type of another key /// path. Calling `appending(path:)` results in the same key path as if the /// given key path had been specified using dot notation. /// /// - Parameter path: The key path to append. /// - Returns: A key path from the root of this key path to the value type of /// `path`. @_inlineable // FIXME(sil-serialize-all) public func appending<Root, Value, AppendedValue>( path: ReferenceWritableKeyPath<Value, AppendedValue> ) -> ReferenceWritableKeyPath<Root, AppendedValue> where Self == KeyPath<Root, Value> { return _appendingKeyPaths(root: self, leaf: path) } } extension _AppendKeyPath /* where Self == WritableKeyPath<T,U> */ { /// Returns a new key path created by appending the given key path to this /// one. /// /// Use this method to extend this key path to the value type of another key /// path. Calling `appending(path:)` results in the same key path as if the /// given key path had been specified using dot notation. /// /// - Parameter path: The key path to append. /// - Returns: A key path from the root of this key path to the value type of /// `path`. @_inlineable // FIXME(sil-serialize-all) public func appending<Root, Value, AppendedValue>( path: WritableKeyPath<Value, AppendedValue> ) -> WritableKeyPath<Root, AppendedValue> where Self == WritableKeyPath<Root, Value> { return _appendingKeyPaths(root: self, leaf: path) } /// Returns a new key path created by appending the given key path to this /// one. /// /// Use this method to extend this key path to the value type of another key /// path. Calling `appending(path:)` results in the same key path as if the /// given key path had been specified using dot notation. /// /// - Parameter path: The key path to append. /// - Returns: A key path from the root of this key path to the value type of /// `path`. @_inlineable // FIXME(sil-serialize-all) public func appending<Root, Value, AppendedValue>( path: ReferenceWritableKeyPath<Value, AppendedValue> ) -> ReferenceWritableKeyPath<Root, AppendedValue> where Self == WritableKeyPath<Root, Value> { return _appendingKeyPaths(root: self, leaf: path) } } extension _AppendKeyPath /* where Self == ReferenceWritableKeyPath<T,U> */ { /// Returns a new key path created by appending the given key path to this /// one. /// /// Use this method to extend this key path to the value type of another key /// path. Calling `appending(path:)` results in the same key path as if the /// given key path had been specified using dot notation. /// /// - Parameter path: The key path to append. /// - Returns: A key path from the root of this key path to the value type of /// `path`. @_inlineable // FIXME(sil-serialize-all) public func appending<Root, Value, AppendedValue>( path: WritableKeyPath<Value, AppendedValue> ) -> ReferenceWritableKeyPath<Root, AppendedValue> where Self == ReferenceWritableKeyPath<Root, Value> { return _appendingKeyPaths(root: self, leaf: path) } } // internal-with-availability @_inlineable // FIXME(sil-serialize-all) public func _tryToAppendKeyPaths<Result: AnyKeyPath>( root: AnyKeyPath, leaf: AnyKeyPath ) -> Result? { let (rootRoot, rootValue) = type(of: root)._rootAndValueType let (leafRoot, leafValue) = type(of: leaf)._rootAndValueType if rootValue != leafRoot { return nil } func open<Root>(_: Root.Type) -> Result { func open2<Value>(_: Value.Type) -> Result { func open3<AppendedValue>(_: AppendedValue.Type) -> Result { let typedRoot = unsafeDowncast(root, to: KeyPath<Root, Value>.self) let typedLeaf = unsafeDowncast(leaf, to: KeyPath<Value, AppendedValue>.self) let result = _appendingKeyPaths(root: typedRoot, leaf: typedLeaf) return unsafeDowncast(result, to: Result.self) } return _openExistential(leafValue, do: open3) } return _openExistential(rootValue, do: open2) } return _openExistential(rootRoot, do: open) } // internal-with-availability @_inlineable // FIXME(sil-serialize-all) public func _appendingKeyPaths< Root, Value, AppendedValue, Result: KeyPath<Root, AppendedValue> >( root: KeyPath<Root, Value>, leaf: KeyPath<Value, AppendedValue> ) -> Result { let resultTy = type(of: root).appendedType(with: type(of: leaf)) return root.withBuffer { var rootBuffer = $0 return leaf.withBuffer { var leafBuffer = $0 // Reserve room for the appended KVC string, if both key paths are // KVC-compatible. let appendedKVCLength: Int, rootKVCLength: Int, leafKVCLength: Int if let rootPtr = root._kvcKeyPathStringPtr, let leafPtr = leaf._kvcKeyPathStringPtr { rootKVCLength = Int(_stdlib_strlen(rootPtr)) leafKVCLength = Int(_stdlib_strlen(leafPtr)) // root + "." + leaf appendedKVCLength = rootKVCLength + 1 + leafKVCLength } else { rootKVCLength = 0 leafKVCLength = 0 appendedKVCLength = 0 } // Result buffer has room for both key paths' components, plus the // header, plus space for the middle type. // Align up the root so that we can put the component type after it. let alignMask = MemoryLayout<Int>.alignment - 1 let rootSize = (rootBuffer.data.count + alignMask) & ~alignMask let resultSize = rootSize + leafBuffer.data.count + 2 * MemoryLayout<Int>.size // Tail-allocate space for the KVC string. let totalResultSize = (resultSize + appendedKVCLength + 3) & ~3 var kvcStringBuffer: UnsafeMutableRawPointer? = nil let result = resultTy._create(capacityInBytes: totalResultSize) { var destBuffer = $0 // Remember where the tail-allocated KVC string buffer begins. if appendedKVCLength > 0 { kvcStringBuffer = destBuffer.baseAddress.unsafelyUnwrapped .advanced(by: resultSize) destBuffer = .init(start: destBuffer.baseAddress, count: resultSize) } func pushRaw(size: Int, alignment: Int) -> UnsafeMutableRawBufferPointer { var baseAddress = destBuffer.baseAddress.unsafelyUnwrapped var misalign = Int(bitPattern: baseAddress) % alignment if misalign != 0 { misalign = alignment - misalign baseAddress = baseAddress.advanced(by: misalign) } let result = UnsafeMutableRawBufferPointer( start: baseAddress, count: size) destBuffer = UnsafeMutableRawBufferPointer( start: baseAddress + size, count: destBuffer.count - size - misalign) return result } func push<T>(_ value: T) { let buf = pushRaw(size: MemoryLayout<T>.size, alignment: MemoryLayout<T>.alignment) buf.storeBytes(of: value, as: T.self) } // Save space for the header. let leafIsReferenceWritable = type(of: leaf).kind == .reference let header = KeyPathBuffer.Header( size: resultSize - MemoryLayout<Int>.size, trivial: rootBuffer.trivial && leafBuffer.trivial, hasReferencePrefix: rootBuffer.hasReferencePrefix || leafIsReferenceWritable ) push(header) // Start the components at pointer alignment _ = pushRaw(size: RawKeyPathComponent.Header.pointerAlignmentSkew, alignment: 4) let leafHasReferencePrefix = leafBuffer.hasReferencePrefix // Clone the root components into the buffer. while true { let (component, type) = rootBuffer.next() let isLast = type == nil // If the leaf appended path has a reference prefix, then the // entire root is part of the reference prefix. let endOfReferencePrefix: Bool if leafHasReferencePrefix { endOfReferencePrefix = false } else if isLast && leafIsReferenceWritable { endOfReferencePrefix = true } else { endOfReferencePrefix = component.header.endOfReferencePrefix } component.clone( into: &destBuffer, endOfReferencePrefix: endOfReferencePrefix) if let type = type { push(type) } else { // Insert our endpoint type between the root and leaf components. push(Value.self as Any.Type) break } } // Clone the leaf components into the buffer. while true { let (component, type) = leafBuffer.next() component.clone( into: &destBuffer, endOfReferencePrefix: component.header.endOfReferencePrefix) if let type = type { push(type) } else { break } } _sanityCheck(destBuffer.count == 0, "did not fill entire result buffer") } // Build the KVC string if there is one. if let kvcStringBuffer = kvcStringBuffer { let rootPtr = root._kvcKeyPathStringPtr.unsafelyUnwrapped let leafPtr = leaf._kvcKeyPathStringPtr.unsafelyUnwrapped _memcpy(dest: kvcStringBuffer, src: UnsafeMutableRawPointer(mutating: rootPtr), size: UInt(rootKVCLength)) kvcStringBuffer.advanced(by: rootKVCLength) .storeBytes(of: 0x2E /* '.' */, as: CChar.self) _memcpy(dest: kvcStringBuffer.advanced(by: rootKVCLength + 1), src: UnsafeMutableRawPointer(mutating: leafPtr), size: UInt(leafKVCLength)) result._kvcKeyPathStringPtr = UnsafePointer(kvcStringBuffer.assumingMemoryBound(to: CChar.self)) kvcStringBuffer.advanced(by: rootKVCLength + leafKVCLength + 1) .storeBytes(of: 0 /* '\0' */, as: CChar.self) } return unsafeDowncast(result, to: Result.self) } } } // The distance in bytes from the address point of a KeyPath object to its // buffer header. Includes the size of the Swift heap object header and the // pointer to the KVC string. @_inlineable // FIXME(sil-serialize-all) @_versioned // FIXME(sil-serialize-all) internal var keyPathObjectHeaderSize: Int { return MemoryLayout<HeapObject>.size + MemoryLayout<Int>.size } // Runtime entry point to instantiate a key path object. @_inlineable // FIXME(sil-serialize-all) @_cdecl("swift_getKeyPath") public func _swift_getKeyPath(pattern: UnsafeMutableRawPointer, arguments: UnsafeRawPointer) -> UnsafeRawPointer { // The key path pattern is laid out like a key path object, with a few // modifications: // - Instead of the two-word object header with isa and refcount, two // pointers to metadata accessors are provided for the root and leaf // value types of the key path. // - The header reuses the "trivial" bit to mean "instantiable in-line", // meaning that the key path described by this pattern has no contextually // dependent parts (no dependence on generic parameters, subscript indexes, // etc.), so it can be set up as a global object once. (The resulting // global object will itself always have the "trivial" bit set, since it // never needs to be destroyed.) // - Components may have unresolved forms that require instantiation. // - Type metadata pointers are unresolved, and instead // point to accessor functions that instantiate the metadata. // // The pattern never precomputes the capabilities of the key path (readonly/ // writable/reference-writable), nor does it encode the reference prefix. // These are resolved dynamically, so that they always reflect the dynamic // capability of the properties involved. let oncePtr = pattern let patternPtr = pattern.advanced(by: MemoryLayout<Int>.size) let bufferPtr = patternPtr.advanced(by: keyPathObjectHeaderSize) // If the pattern is instantiable in-line, do a dispatch_once to // initialize it. (The resulting object will still have the // "trivial" bit set, since a global object never needs destruction.) let bufferHeader = bufferPtr.load(as: KeyPathBuffer.Header.self) bufferHeader.validateReservedBits() if bufferHeader.instantiableInLine { Builtin.onceWithContext(oncePtr._rawValue, _getKeyPath_instantiateInline, patternPtr._rawValue) // Return the instantiated object at +1. // TODO: This will be unnecessary once we support global objects with inert // refcounting. let object = Unmanaged<AnyKeyPath>.fromOpaque(patternPtr) _ = object.retain() return UnsafeRawPointer(patternPtr) } // Otherwise, instantiate a new key path object modeled on the pattern. return _getKeyPath_instantiatedOutOfLine(patternPtr, arguments) } @_inlineable // FIXME(sil-serialize-all) @_versioned // FIXME(sil-serialize-all) internal func _getKeyPath_instantiatedOutOfLine( _ pattern: UnsafeRawPointer, _ arguments: UnsafeRawPointer) -> UnsafeRawPointer { // Do a pass to determine the class of the key path we'll be instantiating // and how much space we'll need for it. let (keyPathClass, rootType, size, alignmentMask) = _getKeyPathClassAndInstanceSizeFromPattern(pattern, arguments) _sanityCheck(alignmentMask < MemoryLayout<Int>.alignment, "overalignment not implemented") // Allocate the instance. let instance = keyPathClass._create(capacityInBytes: size) { instanceData in // Instantiate the pattern into the instance. let patternBufferPtr = pattern.advanced(by: keyPathObjectHeaderSize) let patternBuffer = KeyPathBuffer(base: patternBufferPtr) _instantiateKeyPathBuffer(patternBuffer, instanceData, rootType, arguments) } // Take the KVC string from the pattern. let kvcStringPtr = pattern.advanced(by: MemoryLayout<HeapObject>.size) instance._kvcKeyPathStringPtr = kvcStringPtr .load(as: Optional<UnsafePointer<CChar>>.self) // Hand it off at +1. return UnsafeRawPointer(Unmanaged.passRetained(instance).toOpaque()) } @_inlineable // FIXME(sil-serialize-all) @_versioned // FIXME(sil-serialize-all) internal func _getKeyPath_instantiateInline( _ objectRawPtr: Builtin.RawPointer ) { let objectPtr = UnsafeMutableRawPointer(objectRawPtr) // Do a pass to determine the class of the key path we'll be instantiating // and how much space we'll need for it. // The pattern argument doesn't matter since an in-place pattern should never // have arguments. let (keyPathClass, rootType, instantiatedSize, alignmentMask) = _getKeyPathClassAndInstanceSizeFromPattern(objectPtr, objectPtr) _sanityCheck(alignmentMask < MemoryLayout<Int>.alignment, "overalignment not implemented") let bufferPtr = objectPtr.advanced(by: keyPathObjectHeaderSize) let buffer = KeyPathBuffer(base: bufferPtr) let totalSize = buffer.data.count + MemoryLayout<Int>.size let bufferData = UnsafeMutableRawBufferPointer( start: bufferPtr, count: instantiatedSize) // TODO: Eventually, we'll need to handle cases where the instantiated // key path has a larger size than the pattern (because it involves // resilient types, for example), and fall back to out-of-place instantiation // when that happens. _sanityCheck(instantiatedSize <= totalSize, "size-increasing in-place instantiation not implemented") // Instantiate the pattern in place. _instantiateKeyPathBuffer(buffer, bufferData, rootType, bufferPtr) _swift_instantiateInertHeapObject(objectPtr, unsafeBitCast(keyPathClass, to: OpaquePointer.self)) } internal typealias MetadataAccessor = @convention(c) (UnsafeRawPointer) -> UnsafeRawPointer @_inlineable // FIXME(sil-serialize-all) @_versioned // FIXME(sil-serialize-all) internal func _getKeyPathClassAndInstanceSizeFromPattern( _ pattern: UnsafeRawPointer, _ arguments: UnsafeRawPointer ) -> ( keyPathClass: AnyKeyPath.Type, rootType: Any.Type, size: Int, alignmentMask: Int ) { // Resolve the root and leaf types. let rootAccessor = pattern.load(as: MetadataAccessor.self) let leafAccessor = pattern.load(fromByteOffset: MemoryLayout<Int>.size, as: MetadataAccessor.self) let root = unsafeBitCast(rootAccessor(arguments), to: Any.Type.self) let leaf = unsafeBitCast(leafAccessor(arguments), to: Any.Type.self) // Scan the pattern to figure out the dynamic capability of the key path. // Start off assuming the key path is writable. var capability: KeyPathKind = .value var didChain = false let bufferPtr = pattern.advanced(by: keyPathObjectHeaderSize) var buffer = KeyPathBuffer(base: bufferPtr) var size = buffer.data.count + MemoryLayout<Int>.size var alignmentMask = MemoryLayout<Int>.alignment - 1 while true { let header = buffer.pop(RawKeyPathComponent.Header.self) func popOffset() { if header.payload == RawKeyPathComponent.Header.unresolvedFieldOffsetPayload || header.payload == RawKeyPathComponent.Header.outOfLineOffsetPayload { _ = buffer.pop(UInt32.self) } if header.payload == RawKeyPathComponent.Header.unresolvedIndirectOffsetPayload { _ = buffer.pop(Int.self) // On 64-bit systems the pointer to the ivar offset variable is // pointer-sized and -aligned, but the resulting offset ought to be // 32 bits only and fit into padding between the 4-byte header and // pointer-aligned type word. We don't need this space after // instantiation. if MemoryLayout<Int>.size == 8 { size -= MemoryLayout<UnsafeRawPointer>.size } } } switch header.kind { case .struct: // No effect on the capability. // TODO: we should dynamically prevent "let" properties from being // reassigned. popOffset() case .class: // The rest of the key path could be reference-writable. // TODO: we should dynamically prevent "let" properties from being // reassigned. capability = .reference popOffset() case .computed: let settable = header.payload & RawKeyPathComponent.Header.computedSettableFlag != 0 let mutating = header.payload & RawKeyPathComponent.Header.computedMutatingFlag != 0 let hasArguments = header.payload & RawKeyPathComponent.Header.computedHasArgumentsFlag != 0 switch (settable, mutating) { case (false, false): // If the property is get-only, the capability becomes read-only, unless // we get another reference-writable component. capability = .readOnly case (true, false): capability = .reference case (true, true): // Writable if the base is. No effect. break case (false, true): _sanityCheckFailure("unpossible") } _ = buffer.popRaw(size: MemoryLayout<Int>.size * (settable ? 3 : 2), alignment: MemoryLayout<Int>.alignment) // Get the instantiated size and alignment of the argument payload // by asking the layout function to compute it for our given argument // file. if hasArguments { let getLayoutRaw = buffer.pop(UnsafeRawPointer.self) let _ /*witnesses*/ = buffer.pop(UnsafeRawPointer.self) let _ /*initializer*/ = buffer.pop(UnsafeRawPointer.self) let getLayout = unsafeBitCast(getLayoutRaw, to: RawKeyPathComponent.ComputedArgumentLayoutFn.self) let (addedSize, addedAlignmentMask) = getLayout(arguments) // TODO: Handle over-aligned values _sanityCheck(addedAlignmentMask < MemoryLayout<Int>.alignment, "overaligned computed property element not supported") // Argument payload replaces the space taken by the initializer // function pointer in the pattern. size += (addedSize + alignmentMask) & ~alignmentMask - MemoryLayout<Int>.size } case .optionalChain, .optionalWrap: // Chaining always renders the whole key path read-only. didChain = true break case .optionalForce: // No effect. break } // Break if this is the last component. if buffer.data.count == 0 { break } // Pop the type accessor reference. _ = buffer.popRaw(size: MemoryLayout<Int>.size, alignment: MemoryLayout<Int>.alignment) } // Chaining always renders the whole key path read-only. if didChain { capability = .readOnly } // Grab the class object for the key path type we'll end up with. func openRoot<Root>(_: Root.Type) -> AnyKeyPath.Type { func openLeaf<Leaf>(_: Leaf.Type) -> AnyKeyPath.Type { switch capability { case .readOnly: return KeyPath<Root, Leaf>.self case .value: return WritableKeyPath<Root, Leaf>.self case .reference: return ReferenceWritableKeyPath<Root, Leaf>.self } } return _openExistential(leaf, do: openLeaf) } let classTy = _openExistential(root, do: openRoot) return (keyPathClass: classTy, rootType: root, size: size, alignmentMask: alignmentMask) } @_inlineable // FIXME(sil-serialize-all) @_versioned // FIXME(sil-serialize-all) internal func _instantiateKeyPathBuffer( _ origPatternBuffer: KeyPathBuffer, _ origDestData: UnsafeMutableRawBufferPointer, _ rootType: Any.Type, _ arguments: UnsafeRawPointer ) { // NB: patternBuffer and destData alias when the pattern is instantiable // in-line. Therefore, do not read from patternBuffer after the same position // in destData has been written to. var patternBuffer = origPatternBuffer let destHeaderPtr = origDestData.baseAddress.unsafelyUnwrapped var destData = UnsafeMutableRawBufferPointer( start: destHeaderPtr.advanced(by: MemoryLayout<Int>.size), count: origDestData.count - MemoryLayout<Int>.size) func pushDest<T>(_ value: T) { _sanityCheck(_isPOD(T.self)) var value2 = value let size = MemoryLayout<T>.size let alignment = MemoryLayout<T>.alignment var baseAddress = destData.baseAddress.unsafelyUnwrapped var misalign = Int(bitPattern: baseAddress) % alignment if misalign != 0 { misalign = alignment - misalign baseAddress = baseAddress.advanced(by: misalign) } _memcpy(dest: baseAddress, src: &value2, size: UInt(size)) destData = UnsafeMutableRawBufferPointer( start: baseAddress + size, count: destData.count - size - misalign) } // Track the triviality of the resulting object data. var isTrivial = true // Track where the reference prefix begins. var endOfReferencePrefixComponent: UnsafeMutableRawPointer? = nil var previousComponentAddr: UnsafeMutableRawPointer? = nil // Instantiate components that need it. var base: Any.Type = rootType // Some pattern forms are pessimistically larger than what we need in the // instantiated key path. Keep track of this. while true { let componentAddr = destData.baseAddress.unsafelyUnwrapped let header = patternBuffer.pop(RawKeyPathComponent.Header.self) func tryToResolveOffset() { if header.payload == RawKeyPathComponent.Header.unresolvedFieldOffsetPayload { // Look up offset in type metadata. The value in the pattern is the // offset within the metadata object. let metadataPtr = unsafeBitCast(base, to: UnsafeRawPointer.self) let offsetOfOffset = patternBuffer.pop(UInt32.self) let offset = UInt32(metadataPtr.load(fromByteOffset: Int(offsetOfOffset), as: UInt.self)) // Rewrite the header for a resolved offset. var newHeader = header newHeader.payload = RawKeyPathComponent.Header.outOfLineOffsetPayload pushDest(newHeader) pushDest(offset) return } if header.payload == RawKeyPathComponent.Header.unresolvedIndirectOffsetPayload { // Look up offset in the indirectly-referenced variable we have a // pointer. let offsetVar = patternBuffer.pop(UnsafeRawPointer.self) let offsetValue = UInt32(offsetVar.load(as: UInt.self)) // Rewrite the header for a resolved offset. var newHeader = header newHeader.payload = RawKeyPathComponent.Header.outOfLineOffsetPayload pushDest(newHeader) pushDest(offsetValue) return } // Otherwise, just transfer the pre-resolved component. pushDest(header) if header.payload == RawKeyPathComponent.Header.outOfLineOffsetPayload { let offset = patternBuffer.pop(UInt32.self) pushDest(offset) } } switch header.kind { case .struct: // The offset may need to be resolved dynamically. tryToResolveOffset() case .class: // Crossing a class can end the reference prefix, and makes the following // key path potentially reference-writable. endOfReferencePrefixComponent = previousComponentAddr // The offset may need to be resolved dynamically. tryToResolveOffset() case .optionalChain, .optionalWrap, .optionalForce: // No instantiation necessary. pushDest(header) break case .computed: // A nonmutating settable property can end the reference prefix and // makes the following key path potentially reference-writable. if header.payload & RawKeyPathComponent.Header.computedSettableFlag != 0 && header.payload & RawKeyPathComponent.Header.computedMutatingFlag == 0 { endOfReferencePrefixComponent = previousComponentAddr } // The ID may need resolution if the property is keyed by a selector. var newHeader = header var id = patternBuffer.pop(Int.self) switch header.payload & RawKeyPathComponent.Header.computedIDResolutionMask { case RawKeyPathComponent.Header.computedIDResolved: // Nothing to do. break case RawKeyPathComponent.Header.computedIDUnresolvedIndirectPointer: // The value in the pattern is a pointer to the actual unique word-sized // value in memory. let idPtr = UnsafeRawPointer(bitPattern: id).unsafelyUnwrapped id = idPtr.load(as: Int.self) default: _sanityCheckFailure("unpossible") } newHeader.payload &= ~RawKeyPathComponent.Header.computedIDResolutionMask pushDest(newHeader) pushDest(id) // Carry over the accessors. let getter = patternBuffer.pop(UnsafeRawPointer.self) pushDest(getter) if header.payload & RawKeyPathComponent.Header.computedSettableFlag != 0{ let setter = patternBuffer.pop(UnsafeRawPointer.self) pushDest(setter) } // Carry over the arguments. if header.payload & RawKeyPathComponent.Header.computedHasArgumentsFlag != 0 { let getLayoutRaw = patternBuffer.pop(UnsafeRawPointer.self) let getLayout = unsafeBitCast(getLayoutRaw, to: RawKeyPathComponent.ComputedArgumentLayoutFn.self) let witnesses = patternBuffer.pop( UnsafePointer<ComputedArgumentWitnesses>.self) if let _ = witnesses.pointee.destroy { isTrivial = false } let initializerRaw = patternBuffer.pop(UnsafeRawPointer.self) let initializer = unsafeBitCast(initializerRaw, to: RawKeyPathComponent.ComputedArgumentInitializerFn.self) let (size, alignmentMask) = getLayout(arguments) _sanityCheck(alignmentMask < MemoryLayout<Int>.alignment, "overaligned computed arguments not implemented yet") // The real buffer stride will be rounded up to alignment. let stride = (size + alignmentMask) & ~alignmentMask pushDest(stride) pushDest(witnesses) _sanityCheck(Int(bitPattern: destData.baseAddress) & alignmentMask == 0, "argument destination not aligned") initializer(arguments, destData.baseAddress.unsafelyUnwrapped) destData = UnsafeMutableRawBufferPointer( start: destData.baseAddress.unsafelyUnwrapped + stride, count: destData.count - stride) } } // Break if this is the last component. if patternBuffer.data.count == 0 { break } // Resolve the component type. let componentTyAccessor = patternBuffer.pop(MetadataAccessor.self) base = unsafeBitCast(componentTyAccessor(arguments), to: Any.Type.self) pushDest(base) previousComponentAddr = componentAddr } // We should have traversed both buffers. _sanityCheck(patternBuffer.data.isEmpty && destData.count == 0) // Write out the header. let destHeader = KeyPathBuffer.Header( size: origDestData.count - MemoryLayout<Int>.size, trivial: isTrivial, hasReferencePrefix: endOfReferencePrefixComponent != nil) destHeaderPtr.storeBytes(of: destHeader, as: KeyPathBuffer.Header.self) // Mark the reference prefix if there is one. if let endOfReferencePrefixComponent = endOfReferencePrefixComponent { var componentHeader = endOfReferencePrefixComponent .load(as: RawKeyPathComponent.Header.self) componentHeader.endOfReferencePrefix = true endOfReferencePrefixComponent.storeBytes(of: componentHeader, as: RawKeyPathComponent.Header.self) } }
apache-2.0
devpunk/punknote
punknote/View/Create/VCreateCellTimelineCell.swift
1
9094
import UIKit class VCreateCellTimelineCell:UICollectionViewCell { private weak var viewCircle:UIView! private weak var viewSelected:VCreateCellTimelineCellSelected! private weak var labelDuration:UILabel! private weak var layoutCircleLeft:NSLayoutConstraint! private weak var modelFrame:MCreateFrame? private weak var controller:CCreate? private weak var labelText:UILabel! private var index:IndexPath? private let numberFormatter:NumberFormatter private let selectedSize:CGFloat private let kCircleTop:CGFloat = 15 private let kCircleSize:CGFloat = 60 private let kSelectedMargin:CGFloat = 5 private let kLabelMargin:CGFloat = 4 private let kDurationRight:CGFloat = -10 private let kDurationWidth:CGFloat = 150 private let kDurationHeight:CGFloat = 22 private let kMaxDecimals:Int = 0 private let KMinIntegers:Int = 1 override init(frame:CGRect) { selectedSize = kCircleSize + kSelectedMargin + kSelectedMargin numberFormatter = NumberFormatter() numberFormatter.numberStyle = NumberFormatter.Style.decimal numberFormatter.maximumFractionDigits = kMaxDecimals numberFormatter.minimumIntegerDigits = KMinIntegers numberFormatter.positiveSuffix = NSLocalizedString("VCreateCellTimelineCell_secondsSuffix", comment:"") super.init(frame:frame) clipsToBounds = true backgroundColor = UIColor.clear let viewRibbon:VBorder = VBorder(color:UIColor.punkOrange.withAlphaComponent(0.3)) let circleCornerRadius:CGFloat = kCircleSize / 2.0 let labelCornerRadius:CGFloat = circleCornerRadius - kLabelMargin let viewCircle:UIView = UIView() viewCircle.clipsToBounds = true viewCircle.isUserInteractionEnabled = false viewCircle.translatesAutoresizingMaskIntoConstraints = false viewCircle.backgroundColor = UIColor.clear viewCircle.layer.cornerRadius = circleCornerRadius viewCircle.layer.borderColor = UIColor(white:0, alpha:0.1).cgColor self.viewCircle = viewCircle let viewSelected:VCreateCellTimelineCellSelected = VCreateCellTimelineCellSelected() self.viewSelected = viewSelected let labelDuration:UILabel = UILabel() labelDuration.translatesAutoresizingMaskIntoConstraints = false labelDuration.isUserInteractionEnabled = false labelDuration.font = UIFont.regular(size:14) labelDuration.textColor = UIColor.black labelDuration.backgroundColor = UIColor.clear labelDuration.textAlignment = NSTextAlignment.right self.labelDuration = labelDuration let viewGradient:VGradient = VGradient.diagonal( colorLeftBottom:UIColor.punkPurple, colorTopRight:UIColor.punkOrange) viewGradient.mask = viewSelected let labelText:UILabel = UILabel() labelText.translatesAutoresizingMaskIntoConstraints = false labelText.isUserInteractionEnabled = false labelText.backgroundColor = UIColor.clear labelText.textAlignment = NSTextAlignment.center labelText.numberOfLines = 0 labelText.textColor = UIColor.black labelText.font = UIFont.regular(size:11) labelText.clipsToBounds = true labelText.layer.cornerRadius = labelCornerRadius self.labelText = labelText addSubview(viewRibbon) addSubview(labelDuration) addSubview(labelText) addSubview(viewGradient) addSubview(viewCircle) NSLayoutConstraint.topToTop( view:viewCircle, toView:self, constant:kCircleTop) NSLayoutConstraint.size( view:viewCircle, constant:kCircleSize) layoutCircleLeft = NSLayoutConstraint.leftToLeft( view:viewCircle, toView:self) NSLayoutConstraint.equals( view:viewGradient, toView:self) NSLayoutConstraint.equals( view:labelText, toView:viewCircle, margin:kLabelMargin) NSLayoutConstraint.bottomToBottom( view:viewRibbon, toView:self) NSLayoutConstraint.height( view:viewRibbon, constant:kDurationHeight) NSLayoutConstraint.equalsHorizontal( view:viewRibbon, toView:self) NSLayoutConstraint.bottomToBottom( view:labelDuration, toView:self) NSLayoutConstraint.height( view:labelDuration, constant:kDurationHeight) NSLayoutConstraint.rightToRight( view:labelDuration, toView:self, constant:kDurationRight) NSLayoutConstraint.width( view:labelDuration, constant:kDurationWidth) NotificationCenter.default.addObserver( self, selector:#selector(notifiedTextChanged(sender:)), name:Notification.frameTextChanged, object:nil) } required init?(coder:NSCoder) { return nil } deinit { viewSelected.timer?.invalidate() NotificationCenter.default.removeObserver(self) } override func layoutSubviews() { let width:CGFloat = bounds.maxX let remainCircle:CGFloat = width - kCircleSize let marginLeft:CGFloat = remainCircle / 2.0 layoutCircleLeft.constant = marginLeft let selectedLeft:CGFloat = marginLeft - kSelectedMargin let selectedTop:CGFloat = kCircleTop - kSelectedMargin viewSelected.frame = CGRect( x:selectedLeft, y:selectedTop, width:selectedSize, height:selectedSize) super.layoutSubviews() } override var isSelected:Bool { didSet { hover() } } override var isHighlighted:Bool { didSet { hover() } } //MARK: notifications func notifiedTextChanged(sender notification:Notification) { guard let modelFrame:MCreateFrame = self.modelFrame, let notificationFrame:MCreateFrame = notification.object as? MCreateFrame else { return } if modelFrame === notificationFrame { DispatchQueue.main.async { [weak self] in self?.updateText() } } } //MARK: private private func hover() { guard let modelFrame:MCreateFrame = self.modelFrame else { return } if isSelected || isHighlighted { viewSelected.selected(isSelected:true, model:modelFrame) viewSelected.isHidden = false viewCircle.layer.borderWidth = 0 } else { viewSelected.selected(isSelected:false, model:modelFrame) viewSelected.isHidden = true viewCircle.layer.borderWidth = 1 } checkLast() } private func updateText() { guard let modelFrame:MCreateFrame = self.modelFrame else { return } labelText.text = modelFrame.text } private func checkLast() { guard let controller:CCreate = self.controller, let index:IndexPath = self.index else { return } let countFrames:Int = controller.model.frames.count let currentFrame:Int = index.item + 1 if countFrames == currentFrame { lastCell() } else { notLastCell() } } private func lastCell() { guard let frames:[MCreateFrame] = controller?.model.frames else { return } var duration:TimeInterval = 0 for frame:MCreateFrame in frames { duration += frame.duration } let numberDuration:NSNumber = duration as NSNumber let stringDuration:String? = numberFormatter.string(from:numberDuration) labelDuration.isHidden = false labelDuration.text = stringDuration } private func notLastCell() { labelDuration.isHidden = true } //MARK: public func config(controller:CCreate?, model:MCreateFrame, index:IndexPath) { viewSelected.timer?.invalidate() self.modelFrame = model self.controller = controller self.index = index hover() updateText() } }
mit
abhayamrastogi/ChatSDKPodSpecs
rgconnectsdk/Services/RGChatRoomService.swift
1
2775
// // RGChatRoomService.swift // rgconnectsdk // // Created by Anurag Agnihotri on 21/07/16. // Copyright © 2016 RoundGlass Partners. All rights reserved. // import Foundation public class RGChatRoomService: NSObject { var meteorClient: MeteorClient! public init(meteorClient: MeteorClient) { super.init() } /** Method to fetch list of Chat Rooms from the server from the specified collection. - parameter successCallback: SuccessCallback returns a list of ChatRooms if request is successfull. - parameter errorCallback: ErrorCallback returns an NSError Object if request fails. */ func getChatRooms(successCallback: (chatRooms: [ChatRoom]) -> Void, errorCallback: (error: NSError) -> Void) { ChatRoomNetworkHandler.getChatRooms(self.meteorClient, successCallback: { (chatRooms) in successCallback(chatRooms: chatRooms) }) { (error) in errorCallback(error: error) } } /** Method to create a Public channel with the specified channel name. - parameter channelName: Name to be set for the channel - parameter successCallback: Returns a SuccessCallback if channel is created successfully. - parameter errorCallback: Returns a NSError Object if channel creation failed. */ public func createChannel(channelName: String, successCallback: (response: [NSObject : AnyObject]) -> Void, errorCallback: (error: NSError) -> Void) { ChatRoomNetworkHandler.createChannel(self.meteorClient, channelName: channelName, successCallback: { (response) in successCallback(response: response) }) { (error) in errorCallback(error: error) } } /** Method to create Direct Message with the User whose username is specified. - parameter userName: Name of the User. - parameter successCallback: Returns a SuccessCallback if Direct Message is created successfully. - parameter errorCallback: Returns a NSError Object if request failed. */ public func createDirectMessage(userName: String, successCallback: ((response: [NSObject: AnyObject]) -> Void), errorCallback: ((error: NSError) -> Void)) { ChatRoomNetworkHandler.createDirectMessage(self.meteorClient, userName: userName, successCallback: { (response) in successCallback(response: response) }) { (error) in errorCallback(error: error) } } }
mit
zzycami/MaterialUIKit
MeterialUIKit/MeterialUIKit/AppDelegate.swift
1
2153
// // AppDelegate.swift // MeterialUIKit // // Created by damingdan on 14/12/30. // Copyright (c) 2014年 com.metalmind. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> 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 throttle down OpenGL ES frame rates. 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 inactive 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:. } }
mit
DylanModesitt/Picryption_iOS
Picryption/UploadViewController.swift
1
2626
// // UploadViewController.swift // Picryption // // Created by Dylan C Modesitt on 4/28/17. // Copyright © 2017 Modesitt Systems. All rights reserved. // import UIKit import Photos class UploadViewController: UIViewController, UINavigationControllerDelegate { // MARK: -Variables @IBOutlet weak var uploadButton: UIButton! @IBOutlet weak var pageControl: UIPageControl! var imagePicker = UIImagePickerController() var image: UIImage? // MARK: - View Controller Lifecycle override func viewDidLoad() { managePermissions() } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == Segues.goToMessage { let vc = segue.destination as? MessageViewController vc?.image = image } } // MARK: - IB Methods @IBAction func uploadImage(_ sender: Any) { if UIImagePickerController.isSourceTypeAvailable(.savedPhotosAlbum){ setImagePickerPreferences() self.present(imagePicker, animated: true, completion: nil) } } } extension UploadViewController: UIImagePickerControllerDelegate { func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) { self.dismiss(animated: true, completion: { () -> Void in print("Image view controller was dimissed") }) if let pickedImage = info["UIImagePickerControllerOriginalImage"] as? UIImage { self.image = pickedImage self.performSegue(withIdentifier: Segues.goToMessage, sender: self) } } } // Methods Extensions extension UploadViewController { func managePermissions() { let status = PHPhotoLibrary.authorizationStatus() switch status { case .authorized: print("Authorized") break case .denied, .restricted : UIAlertView.simpleAlert(withTitle: "Picryption Requires Photo Access", andMessage: "Please go to your settings -> Privacy -> Photo & Video and enable Picryption to use your photos!").show() case .notDetermined: // ask for permissions PHPhotoLibrary.requestAuthorization() { status in } } } func setImagePickerPreferences() { print("Setting preferences") imagePicker.delegate = self imagePicker.sourceType = .savedPhotosAlbum; imagePicker.allowsEditing = false } }
mit
csjlengxiang/PullToRefreshSwift
Example/PullToRefreshSwift/ArrayExtension.swift
3
336
// // ArrayExtention.swift // PullToRefreshSwift // // Created by 波戸 勇二 on 12/11/14. // Copyright (c) 2014 Yuji Hato. All rights reserved. // import Foundation extension Array { mutating func shuffle() { for _ in 0..<self.count { sort { (_,_) in arc4random() < arc4random() } } } }
mit
lrosa007/ghoul
gool/ViewController.swift
2
1527
// // ViewController.swift // gool // // Created by Janet on 3/17/16. // Copyright © 2016 Dead Squad. All rights reserved. // import UIKit class ViewController: UIViewController { let borderAlpha : CGFloat = 0.7 let cornerRadius : CGFloat = 5.0 @IBOutlet weak var load: UIButton! @IBOutlet weak var new: UIButton! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib self.refresh() load.frame = CGRectMake(100, 100, 200, 40) load.setTitleColor(UIColor.whiteColor(), forState: UIControlState.Normal) load.backgroundColor = UIColor.clearColor() load.layer.borderWidth = 1.0 load.layer.borderColor = UIColor(white: 1.0, alpha: borderAlpha).CGColor load.layer.cornerRadius = cornerRadius new.frame = CGRectMake(100, 100, 200, 40) new.setTitleColor(UIColor.whiteColor(), forState: UIControlState.Normal) new.backgroundColor = UIColor.clearColor() new.layer.borderWidth = 1.0 new.layer.borderColor = UIColor(white: 1.0, alpha: borderAlpha).CGColor new.layer.cornerRadius = cornerRadius } override func viewWillTransitionToSize(size: CGSize, withTransitionCoordinator coordinator: UIViewControllerTransitionCoordinator) { coordinator.animateAlongsideTransition(nil, completion: { _ in self.refresh() }) } }
gpl-2.0
JustinGuedes/SwiftSpec
Example/Tests/AnySpecificationTests.swift
1
774
// // AnySpecificationTests.swift // SwiftSpec_Tests // // Created by Justin Guedes on 2017/06/13. // Copyright © 2017 CocoaPods. All rights reserved. // import XCTest import SwiftSpec class AnySpecificationTests: XCTestCase { func testShouldWrapSpecificationInAnySpecificationStruct() { let testSpec = DummySpecification(satisfied: true) let anySpec = AnySpecification(testSpec) let result = anySpec.isSatisfied(by: "Any") XCTAssertTrue(result) } func testShouldWrapAnotherSpecificationInAnySpecificationStruct() { let testSpec = DummySpecification(satisfied: false) let anySpec = AnySpecification(testSpec) let result = anySpec.isSatisfied(by: "Any") XCTAssertFalse(result) } }
mit
pmtao/SwiftUtilityFramework
SwiftUtilityFramework/UIKit/UIModule/WebView/BetterWKWebView.swift
1
5692
// // BetterWKWebView.swift // SwiftUtilityFramework // // Created by 阿涛 on 18-7-24. // Copyright © 2019年 SinkingSoul. All rights reserved. // import WebKit /// 常用 WKWebView 注入脚本 public struct CommonWKWebViewScript { /// 解决 html 显示时字体过小的脚本 static public let fontSizeBiggerScript = """ var meta = document.createElement('meta'); meta.setAttribute('name', 'viewport'); meta.setAttribute('content', 'width=device-width'); document.getElementsByTagName('head')[0].appendChild(meta); """ /// 禁止缩放脚本 static public let unscalableScript = """ var meta = document.createElement('meta'); meta.setAttribute('name', 'viewport'); meta.setAttribute('content', 'initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0, user-scalable=no'); document.getElementsByTagName('head')[0].appendChild(meta); """ /// 禁止横屏时自动调整字体大小 static public let fontSizeAdjustScript = """ var style = document.createElement('style'); style.setAttribute('type', 'text/css'); style.innerHTML = 'body { -webkit-text-size-adjust: 100%; }'; document.getElementsByTagName('head')[0].appendChild(style); """ /// 禁用链接长按时弹出菜单 static public let forbidTouchCallout = "document.documentElement.style.webkitTouchCallout='none';" /// 获取选中的文本 static public let getSelectedStringScript = "window.getSelection().toString()" } /// 针对常见问题优化过的 WKWebView open class BetterWKWebView: WKWebView { // MARK: --初始化方法----------- public required init?(coder: NSCoder) { super.init(coder: coder) } public override init(frame: CGRect, configuration: WKWebViewConfiguration) { super.init(frame: frame, configuration: configuration) } /// 使用包含默认优化脚本的配置文件进行初始化 public convenience init(frame: CGRect) { self.init(frame: frame, configuration: BetterWKWebView.defaultScriptedConfiguration()) } /// 生成包含默认优化脚本的配置文件 public static func defaultScriptedConfiguration( _ scriptSources: [String] = [CommonWKWebViewScript.fontSizeBiggerScript, CommonWKWebViewScript.unscalableScript, CommonWKWebViewScript.fontSizeAdjustScript], messageHandler: WKScriptMessageHandler? = nil, handlerName: String? = nil) -> WKWebViewConfiguration { let webConfiguration = WKWebViewConfiguration() let UserScripts = importScriptSources(scriptSources) let userContentController = setScriptController(UserScripts, messageHandler: messageHandler, named: handlerName) webConfiguration.userContentController = userContentController return webConfiguration } // MARK: --脚本注入相关方法-------------------👇 /// 导入自定义脚本文件(支持导入多个。) /// /// - Parameter names: 脚本名称数组:[a.js, b.js, c.js...] /// - Returns: 可注入的脚本对象 public static func importScriptFiles( _ scriptNames: [String], injectionTime: WKUserScriptInjectionTime = .atDocumentEnd, forMainFrameOnly: Bool = false) -> [WKUserScript] { var UserScripts = [WKUserScript]() let bundle = Bundle.init(for: self) for name in scriptNames { let scriptPath = bundle.path(forResource: name, ofType: "js") let script = try! String(contentsOfFile: scriptPath!, encoding: .utf8) UserScripts.append(WKUserScript(source: script, injectionTime: injectionTime, forMainFrameOnly: forMainFrameOnly)) } return UserScripts } /// 导入自定义脚本源码(直接输入源码字符串,支持导入多个。) /// /// - Parameter sources: 脚本源码字符串数组:["source1", "source2", "source3"...] /// - Returns: 可注入的脚本对象 public static func importScriptSources( _ scriptSources: [String], injectionTime: WKUserScriptInjectionTime = .atDocumentEnd, forMainFrameOnly: Bool = false) -> [WKUserScript] { var UserScripts = [WKUserScript]() for scriptSource in scriptSources { UserScripts.append(WKUserScript(source: scriptSource, injectionTime: injectionTime, forMainFrameOnly: forMainFrameOnly)) } return UserScripts } /// 设置脚本控制器 /// /// - Parameter userScripts: 可注入的脚本对象 /// - Returns: WKUserContentController 对象 public static func setScriptController(_ userScripts: [WKUserScript], messageHandler: WKScriptMessageHandler? = nil, named handlerName: String? = nil) -> WKUserContentController { let userContentController = WKUserContentController() for userScript in userScripts { userContentController.addUserScript(userScript) } if messageHandler != nil && handlerName != nil { userContentController.add(messageHandler!, name: handlerName!) } return userContentController } }
mit
ramonvasc/MXLCalendarManagerSwift
MXLCalendarManagerSwift/MXLCalendarManager.swift
1
20457
// // MXLCalendarManager.swift // Pods // // Created by Ramon Vasconcelos on 25/08/2017. // // // 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 Foundation #if os(iOS) import UIKit #endif public class MXLCalendarManager { public init() {} public func scanICSFileAtRemoteURL(fileURL: URL, withCompletionHandler callback: @escaping (MXLCalendar?, Error?) -> Void) { #if os(iOS) UIApplication.shared.isNetworkActivityIndicatorVisible = true #endif var fileData = Data() DispatchQueue.global(qos: .default).async { do { fileData = try Data(contentsOf: fileURL) } catch (let downloadError) { #if os(iOS) UIApplication.shared.isNetworkActivityIndicatorVisible = false #endif callback(nil, downloadError) return } DispatchQueue.main.async { #if os(iOS) UIApplication.shared.isNetworkActivityIndicatorVisible = false #endif guard let fileString = String(data: fileData, encoding: .utf8) else { return } self.parse(icsString: fileString, withCompletionHandler: callback) } } } public func scanICSFileatLocalPath(filePath: String, withCompletionHandler callback: @escaping (MXLCalendar?, Error?) -> Void) { var calendarFile = String() do { calendarFile = try String(contentsOfFile: filePath, encoding: .utf8) } catch (let fileError) { callback(nil, fileError) return } parse(icsString: calendarFile, withCompletionHandler: callback) } func createAttendee(string: String) -> MXLCalendarAttendee? { var eventScanner = Scanner(string: string) var uri = String() var role = String() var comomName = String() var uriPointer: NSString? var attributesPointer: NSString? var holderPointer: NSString? eventScanner.scanUpTo(":", into: &attributesPointer) eventScanner.scanUpTo("\n", into: &uriPointer) if let uriPointer = uriPointer { uri = (uriPointer.substring(from: 1)) } if let attributesPointer = attributesPointer { eventScanner = Scanner(string: attributesPointer as String) eventScanner.scanUpTo("ROLE", into: nil) eventScanner.scanUpTo(";", into: &holderPointer) if let holderPointer = holderPointer { role = holderPointer.replacingOccurrences(of: "ROLE", with: "") } eventScanner = Scanner(string: attributesPointer as String) eventScanner.scanUpTo("CN", into: nil) eventScanner.scanUpTo(";", into: &holderPointer) if let holderPointer = holderPointer { comomName = holderPointer.replacingOccurrences(of: "CN", with: "") } } guard let roleEnum = Role(rawValue: role) else { return nil } return MXLCalendarAttendee(withRole: roleEnum, commonName: comomName, andUri: uri) } public func parse(icsString: String, withCompletionHandler callback: @escaping (MXLCalendar?, Error?) -> Void) { var regex = NSRegularExpression() do { regex = try NSRegularExpression(pattern: "\n +", options: .caseInsensitive) } catch (let error) { print(error) } let range = NSRange(location: 0, length: (icsString as NSString).length) let icsStringWithoutNewLines = regex.stringByReplacingMatches(in: icsString, options: NSRegularExpression.MatchingOptions(rawValue: 0), range: range, withTemplate: "") // Pull out each line from the calendar file var eventsArray = icsStringWithoutNewLines.components(separatedBy: "BEGIN:VEVENT") let calendar = MXLCalendar() var calendarStringPointer: NSString? var calendarString = String() // Remove the first item (that's just all the stuff before the first VEVENT) if eventsArray.count > 0 { let scanner = Scanner(string: eventsArray[0]) scanner.scanUpTo("TZID:", into: nil) scanner.scanUpTo("\n", into: &calendarStringPointer) calendarString = String(calendarStringPointer ?? "") calendarString = calendarString.replacingOccurrences(of: "\n", with: "").replacingOccurrences(of: "\r", with: "").replacingOccurrences(of: "TZID", with: "") eventsArray.remove(at: 0) } var eventScanner = Scanner() // For each event, extract the data for event in eventsArray { var timezoneIDStringPointer: NSString? var timezoneIDString = String() var startDateTimeStringPointer: NSString? var startDateTimeString = String() var endDateTimeStringPointer: NSString? var endDateTimeString = String() var eventUniqueIDStringPointer: NSString? var eventUniqueIDString = String() var recurrenceIDStringPointer: NSString? var recurrenceIDString = String() var createdDateTimeStringPointer: NSString? var createdDateTimeString = String() var descriptionStringPointer: NSString? var descriptionString = String() var lastModifiedDateTimeStringPointer: NSString? var lastModifiedDateTimeString = String() var locationStringPointer: NSString? var locationString = String() var sequenceStringPointer: NSString? var sequenceString = String() var statusStringPointer: NSString? var statusString = String() var summaryStringPointer: NSString? var summaryString = String() var transStringPointer: NSString? var transString = String() var timeStampStringPointer: NSString? var timeStampString = String() var repetitionStringPointer: NSString? var repetitionString = String() var exceptionRuleStringPointer: NSString? var exceptionRuleString = String() var exceptionDates = [String]() var attendees = [MXLCalendarAttendee]() // Extract event time zone ID eventScanner = Scanner(string: event) eventScanner.scanUpTo("DTSTART;TZID=", into: nil) eventScanner.scanUpTo(":", into: &timezoneIDStringPointer) timezoneIDString = String(timezoneIDStringPointer ?? "") timezoneIDString = timezoneIDString.replacingOccurrences(of: "DTSTART;TZID=", with: "").replacingOccurrences(of: "\n", with: "") if timezoneIDString.isEmpty { // Extract event time zone ID eventScanner = Scanner(string: event) eventScanner.scanUpTo("TZID:", into: nil) eventScanner.scanUpTo("\n", into: &timezoneIDStringPointer) timezoneIDString = String(timezoneIDStringPointer ?? "") timezoneIDString = timezoneIDString.replacingOccurrences(of: "TZID:", with: "").replacingOccurrences(of: "\n", with: "") } // Extract start time eventScanner = Scanner(string: event) eventScanner.scanUpTo(String(format: "DTSTART;TZID=%@:", timezoneIDString), into: nil) eventScanner.scanUpTo("\n", into: &startDateTimeStringPointer) startDateTimeString = String(startDateTimeStringPointer ?? "") startDateTimeString = startDateTimeString.replacingOccurrences(of: String(format: "DTSTART;TZID=%@:", timezoneIDString), with: "").replacingOccurrences(of: "\r", with: "") if startDateTimeString.isEmpty { eventScanner = Scanner(string: event) eventScanner.scanUpTo("DTSTART:", into: nil) eventScanner.scanUpTo("\n", into: &startDateTimeStringPointer) startDateTimeString = String(startDateTimeStringPointer ?? "") startDateTimeString = startDateTimeString.replacingOccurrences(of: "DTSTART:", with: "").replacingOccurrences(of: "\r", with: "") if startDateTimeString.isEmpty { eventScanner = Scanner(string: event) eventScanner.scanUpTo("DTSTART;VALUE=DATE:", into: nil) eventScanner.scanUpTo("\n", into: &startDateTimeStringPointer) startDateTimeString = String(startDateTimeStringPointer ?? "") startDateTimeString = startDateTimeString.replacingOccurrences(of: "DTSTART;VALUE=DATE:", with: "").replacingOccurrences(of: "\r", with: "") } } // Extract end time eventScanner = Scanner(string: event) eventScanner.scanUpTo(String(format: "DTEND;TZID=%@:", timezoneIDString), into: nil) eventScanner.scanUpTo("\n", into: &endDateTimeStringPointer) endDateTimeString = String(endDateTimeStringPointer ?? "") endDateTimeString = endDateTimeString.replacingOccurrences(of: String(format: "DTEND;TZID=%@:", timezoneIDString), with: "").replacingOccurrences(of: "\r", with: "") if endDateTimeString.isEmpty { eventScanner = Scanner(string: event) eventScanner.scanUpTo("DTEND:", into: nil) eventScanner.scanUpTo("\n", into: &endDateTimeStringPointer) endDateTimeString = String(endDateTimeStringPointer ?? "") endDateTimeString = endDateTimeString.replacingOccurrences(of: "DTEND:", with: "").replacingOccurrences(of: "\r", with: "") if endDateTimeString.isEmpty { eventScanner = Scanner(string: event) eventScanner.scanUpTo("DTEND;VALUE=DATE:", into: nil) eventScanner.scanUpTo("\n", into: &endDateTimeStringPointer) endDateTimeString = String(endDateTimeStringPointer ?? "") endDateTimeString = endDateTimeString.replacingOccurrences(of: "DTEND;VALUE=DATE:", with: "").replacingOccurrences(of: "\r", with: "") } } // Extract timestamp eventScanner = Scanner(string: event) eventScanner.scanUpTo("DTSTAMP:", into: nil) eventScanner.scanUpTo("\n", into: &timeStampStringPointer) timeStampString = String(timeStampStringPointer ?? "") timeStampString = timeStampString.replacingOccurrences(of: "DTSTAMP:", with: "").replacingOccurrences(of: "\r", with: "") // Extract the unique ID eventScanner = Scanner(string: event) eventScanner.scanUpTo("UID:", into: nil) eventScanner.scanUpTo("\n", into: &eventUniqueIDStringPointer) eventUniqueIDString = String(eventUniqueIDStringPointer ?? "") eventUniqueIDString = eventUniqueIDString.replacingOccurrences(of: "UID:", with: "").replacingOccurrences(of: "\r", with: "") // Extract the attendees eventScanner = Scanner(string: event) var scannerStatus = Bool() repeat { var attendeeStringPointer: NSString? var attendeeString = String() if eventScanner.scanUpTo("ATTENDEE;", into: nil) { scannerStatus = eventScanner.scanUpTo("\n", into: &attendeeStringPointer) attendeeString = String(attendeeStringPointer ?? "") if scannerStatus, !attendeeString.isEmpty { attendeeString = attendeeString.replacingOccurrences(of: "ATTENDEE;", with: "").replacingOccurrences(of: "\r", with: "") if let attendee = createAttendee(string: attendeeString) { attendees.append(attendee) } } } else { scannerStatus = false } } while scannerStatus // Extract the recurrance ID eventScanner = Scanner(string: event) eventScanner.scanUpTo(String(format: "RECURRENCE-ID;TZID=%@:", timezoneIDString), into: nil) eventScanner.scanUpTo("\n", into: &recurrenceIDStringPointer) recurrenceIDString = String(recurrenceIDStringPointer ?? "") recurrenceIDString = recurrenceIDString.replacingOccurrences(of: String(format: "RECURRENCE-ID;TZID=%@:", timezoneIDString), with: "").replacingOccurrences(of: "\r", with: "") // Extract the created datetime eventScanner = Scanner(string: event) eventScanner.scanUpTo("CREATED:", into: nil) eventScanner.scanUpTo("\n", into: &createdDateTimeStringPointer) createdDateTimeString = String(createdDateTimeStringPointer ?? "") createdDateTimeString = createdDateTimeString.replacingOccurrences(of: "CREATED:", with: "").replacingOccurrences(of: "\r", with: "") // Extract event description eventScanner = Scanner(string: event) eventScanner.scanUpTo("DESCRIPTION:", into: nil) eventScanner.scanUpTo("\n", into: &descriptionStringPointer) descriptionString = String(descriptionStringPointer ?? "") descriptionString = descriptionString.replacingOccurrences(of: "DESCRIPTION:", with: "").replacingOccurrences(of: "\r", with: "") // Extract last modified datetime eventScanner = Scanner(string: event) eventScanner.scanUpTo("LAST-MODIFIED:", into: nil) eventScanner.scanUpTo("\n", into: &lastModifiedDateTimeStringPointer) lastModifiedDateTimeString = String(lastModifiedDateTimeStringPointer ?? "") lastModifiedDateTimeString = lastModifiedDateTimeString.replacingOccurrences(of: "LAST-MODIFIED:", with: "").replacingOccurrences(of: "\n", with: "").replacingOccurrences(of: "\r", with: "") // Extract the event location eventScanner = Scanner(string: event) eventScanner.scanUpTo("LOCATION:", into: nil) eventScanner.scanUpTo("\n", into: &locationStringPointer) locationString = String(locationStringPointer ?? "") locationString = locationString.replacingOccurrences(of: "LOCATION:", with: "").replacingOccurrences(of: "\n", with: "").replacingOccurrences(of: "\r", with: "") // Extract the event sequence eventScanner = Scanner(string: event) eventScanner.scanUpTo("SEQUENCE:", into: nil) eventScanner.scanUpTo("\n", into: &sequenceStringPointer) sequenceString = String(sequenceStringPointer ?? "") sequenceString = sequenceString.replacingOccurrences(of: "SEQUENCE:", with: "").replacingOccurrences(of: "\n", with: "").replacingOccurrences(of: "\r", with: "") // Extract the event status eventScanner = Scanner(string: event) eventScanner.scanUpTo("STATUS:", into: nil) eventScanner.scanUpTo("\n", into: &statusStringPointer) statusString = String(statusStringPointer ?? "") statusString = statusString.replacingOccurrences(of: "STATUS:", with: "").replacingOccurrences(of: "\n", with: "").replacingOccurrences(of: "\r", with: "") // Extract the event summary eventScanner = Scanner(string: event) eventScanner.scanUpTo("SUMMARY:", into: nil) eventScanner.scanUpTo("\n", into: &summaryStringPointer) summaryString = String(summaryStringPointer ?? "") summaryString = summaryString.replacingOccurrences(of: "SUMMARY:", with: "").replacingOccurrences(of: "\n", with: "").replacingOccurrences(of: "\r", with: "") // Extract the event transString eventScanner = Scanner(string: event) eventScanner.scanUpTo("TRANSP:", into: nil) eventScanner.scanUpTo("\n", into: &transStringPointer) transString = String(transStringPointer ?? "") transString = transString.replacingOccurrences(of: "TRANSP:", with: "").replacingOccurrences(of: "\n", with: "").replacingOccurrences(of: "\r", with: "") // Extract the event repetition rules eventScanner = Scanner(string: event) eventScanner.scanUpTo("RRULE:", into: nil) eventScanner.scanUpTo("\n", into: &repetitionStringPointer) repetitionString = String(repetitionStringPointer ?? "") repetitionString = repetitionString.replacingOccurrences(of: "RRULE:", with: "").replacingOccurrences(of: "\n", with: "").replacingOccurrences(of: "\r", with: "") // Extract the event exception rules eventScanner = Scanner(string: event) eventScanner.scanUpTo("EXRULE:", into: nil) eventScanner.scanUpTo("\n", into: &exceptionRuleStringPointer) exceptionRuleString = String(exceptionRuleStringPointer ?? "") exceptionRuleString = exceptionRuleString.replacingOccurrences(of: "EXRULE:", with: "").replacingOccurrences(of: "\n", with: "").replacingOccurrences(of: "\r", with: "") // Set up scanner for eventScanner = Scanner(string: event) eventScanner.scanUpTo("EXDATE:", into: nil) while !eventScanner.isAtEnd { eventScanner.scanUpTo(":", into: nil) var exceptionStringPointer: NSString? var exceptionString = String() eventScanner.scanUpTo("\n", into: &exceptionStringPointer) exceptionString = String(exceptionStringPointer ?? "") exceptionString = exceptionString.replacingOccurrences(of: ":", with: "").replacingOccurrences(of: "\n", with: "").replacingOccurrences(of: "\r", with: "") if !exceptionString.isEmpty { exceptionDates.append(exceptionString) } eventScanner.scanUpTo("EXDATE;", into: nil) } let calendarEvent = MXLCalendarEvent(withStartDate: startDateTimeString, endDate: endDateTimeString, createdAt: createdDateTimeString, lastModified: lastModifiedDateTimeString, uniqueID: eventUniqueIDString, recurrenceID: recurrenceIDString, summary: summaryString, description: descriptionString, location: locationString, status: statusString, recurrenceRules: repetitionString, exceptionDates: exceptionDates, exceptionRules: exceptionRuleString, timeZoneIdentifier: timezoneIDString, attendees: attendees) calendar.add(event: calendarEvent) } callback(calendar, nil) } }
mit
noppoMan/aws-sdk-swift
Sources/Soto/Services/IoTAnalytics/IoTAnalytics_API.swift
1
20629
//===----------------------------------------------------------------------===// // // This source file is part of the Soto for AWS open source project // // Copyright (c) 2017-2020 the Soto project authors // Licensed under Apache License v2.0 // // See LICENSE.txt for license information // See CONTRIBUTORS.txt for the list of Soto project authors // // SPDX-License-Identifier: Apache-2.0 // //===----------------------------------------------------------------------===// // THIS FILE IS AUTOMATICALLY GENERATED by https://github.com/soto-project/soto/tree/main/CodeGenerator. DO NOT EDIT. @_exported import SotoCore /* Client object for interacting with AWS IoTAnalytics service. AWS IoT Analytics allows you to collect large amounts of device data, process messages, and store them. You can then query the data and run sophisticated analytics on it. AWS IoT Analytics enables advanced data exploration through integration with Jupyter Notebooks and data visualization through integration with Amazon QuickSight. Traditional analytics and business intelligence tools are designed to process structured data. IoT data often comes from devices that record noisy processes (such as temperature, motion, or sound). As a result the data from these devices can have significant gaps, corrupted messages, and false readings that must be cleaned up before analysis can occur. Also, IoT data is often only meaningful in the context of other data from external sources. AWS IoT Analytics automates the steps required to analyze data from IoT devices. AWS IoT Analytics filters, transforms, and enriches IoT data before storing it in a time-series data store for analysis. You can set up the service to collect only the data you need from your devices, apply mathematical transforms to process the data, and enrich the data with device-specific metadata such as device type and location before storing it. Then, you can analyze your data by running queries using the built-in SQL query engine, or perform more complex analytics and machine learning inference. AWS IoT Analytics includes pre-built models for common IoT use cases so you can answer questions like which devices are about to fail or which customers are at risk of abandoning their wearable devices. */ public struct IoTAnalytics: AWSService { // MARK: Member variables public let client: AWSClient public let config: AWSServiceConfig // MARK: Initialization /// Initialize the IoTAnalytics client /// - parameters: /// - client: AWSClient used to process requests /// - region: Region of server you want to communicate with. This will override the partition parameter. /// - partition: AWS partition where service resides, standard (.aws), china (.awscn), government (.awsusgov). /// - endpoint: Custom endpoint URL to use instead of standard AWS servers /// - timeout: Timeout value for HTTP requests public init( client: AWSClient, region: SotoCore.Region? = nil, partition: AWSPartition = .aws, endpoint: String? = nil, timeout: TimeAmount? = nil, byteBufferAllocator: ByteBufferAllocator = ByteBufferAllocator(), options: AWSServiceConfig.Options = [] ) { self.client = client self.config = AWSServiceConfig( region: region, partition: region?.partition ?? partition, service: "iotanalytics", serviceProtocol: .restjson, apiVersion: "2017-11-27", endpoint: endpoint, errorType: IoTAnalyticsErrorType.self, timeout: timeout, byteBufferAllocator: byteBufferAllocator, options: options ) } // MARK: API Calls /// Sends messages to a channel. public func batchPutMessage(_ input: BatchPutMessageRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<BatchPutMessageResponse> { return self.client.execute(operation: "BatchPutMessage", path: "/messages/batch", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop) } /// Cancels the reprocessing of data through the pipeline. public func cancelPipelineReprocessing(_ input: CancelPipelineReprocessingRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<CancelPipelineReprocessingResponse> { return self.client.execute(operation: "CancelPipelineReprocessing", path: "/pipelines/{pipelineName}/reprocessing/{reprocessingId}", httpMethod: .DELETE, serviceConfig: self.config, input: input, logger: logger, on: eventLoop) } /// Creates a channel. A channel collects data from an MQTT topic and archives the raw, unprocessed messages before publishing the data to a pipeline. public func createChannel(_ input: CreateChannelRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<CreateChannelResponse> { return self.client.execute(operation: "CreateChannel", path: "/channels", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop) } /// Creates a data set. A data set stores data retrieved from a data store by applying a "queryAction" (a SQL query) or a "containerAction" (executing a containerized application). This operation creates the skeleton of a data set. The data set can be populated manually by calling "CreateDatasetContent" or automatically according to a "trigger" you specify. public func createDataset(_ input: CreateDatasetRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<CreateDatasetResponse> { return self.client.execute(operation: "CreateDataset", path: "/datasets", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop) } /// Creates the content of a data set by applying a "queryAction" (a SQL query) or a "containerAction" (executing a containerized application). public func createDatasetContent(_ input: CreateDatasetContentRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<CreateDatasetContentResponse> { return self.client.execute(operation: "CreateDatasetContent", path: "/datasets/{datasetName}/content", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop) } /// Creates a data store, which is a repository for messages. public func createDatastore(_ input: CreateDatastoreRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<CreateDatastoreResponse> { return self.client.execute(operation: "CreateDatastore", path: "/datastores", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop) } /// Creates a pipeline. A pipeline consumes messages from a channel and allows you to process the messages before storing them in a data store. You must specify both a channel and a datastore activity and, optionally, as many as 23 additional activities in the pipelineActivities array. public func createPipeline(_ input: CreatePipelineRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<CreatePipelineResponse> { return self.client.execute(operation: "CreatePipeline", path: "/pipelines", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop) } /// Deletes the specified channel. @discardableResult public func deleteChannel(_ input: DeleteChannelRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<Void> { return self.client.execute(operation: "DeleteChannel", path: "/channels/{channelName}", httpMethod: .DELETE, serviceConfig: self.config, input: input, logger: logger, on: eventLoop) } /// Deletes the specified data set. You do not have to delete the content of the data set before you perform this operation. @discardableResult public func deleteDataset(_ input: DeleteDatasetRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<Void> { return self.client.execute(operation: "DeleteDataset", path: "/datasets/{datasetName}", httpMethod: .DELETE, serviceConfig: self.config, input: input, logger: logger, on: eventLoop) } /// Deletes the content of the specified data set. @discardableResult public func deleteDatasetContent(_ input: DeleteDatasetContentRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<Void> { return self.client.execute(operation: "DeleteDatasetContent", path: "/datasets/{datasetName}/content", httpMethod: .DELETE, serviceConfig: self.config, input: input, logger: logger, on: eventLoop) } /// Deletes the specified data store. @discardableResult public func deleteDatastore(_ input: DeleteDatastoreRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<Void> { return self.client.execute(operation: "DeleteDatastore", path: "/datastores/{datastoreName}", httpMethod: .DELETE, serviceConfig: self.config, input: input, logger: logger, on: eventLoop) } /// Deletes the specified pipeline. @discardableResult public func deletePipeline(_ input: DeletePipelineRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<Void> { return self.client.execute(operation: "DeletePipeline", path: "/pipelines/{pipelineName}", httpMethod: .DELETE, serviceConfig: self.config, input: input, logger: logger, on: eventLoop) } /// Retrieves information about a channel. public func describeChannel(_ input: DescribeChannelRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<DescribeChannelResponse> { return self.client.execute(operation: "DescribeChannel", path: "/channels/{channelName}", httpMethod: .GET, serviceConfig: self.config, input: input, logger: logger, on: eventLoop) } /// Retrieves information about a data set. public func describeDataset(_ input: DescribeDatasetRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<DescribeDatasetResponse> { return self.client.execute(operation: "DescribeDataset", path: "/datasets/{datasetName}", httpMethod: .GET, serviceConfig: self.config, input: input, logger: logger, on: eventLoop) } /// Retrieves information about a data store. public func describeDatastore(_ input: DescribeDatastoreRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<DescribeDatastoreResponse> { return self.client.execute(operation: "DescribeDatastore", path: "/datastores/{datastoreName}", httpMethod: .GET, serviceConfig: self.config, input: input, logger: logger, on: eventLoop) } /// Retrieves the current settings of the AWS IoT Analytics logging options. public func describeLoggingOptions(_ input: DescribeLoggingOptionsRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<DescribeLoggingOptionsResponse> { return self.client.execute(operation: "DescribeLoggingOptions", path: "/logging", httpMethod: .GET, serviceConfig: self.config, input: input, logger: logger, on: eventLoop) } /// Retrieves information about a pipeline. public func describePipeline(_ input: DescribePipelineRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<DescribePipelineResponse> { return self.client.execute(operation: "DescribePipeline", path: "/pipelines/{pipelineName}", httpMethod: .GET, serviceConfig: self.config, input: input, logger: logger, on: eventLoop) } /// Retrieves the contents of a data set as pre-signed URIs. public func getDatasetContent(_ input: GetDatasetContentRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<GetDatasetContentResponse> { return self.client.execute(operation: "GetDatasetContent", path: "/datasets/{datasetName}/content", httpMethod: .GET, serviceConfig: self.config, input: input, logger: logger, on: eventLoop) } /// Retrieves a list of channels. public func listChannels(_ input: ListChannelsRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<ListChannelsResponse> { return self.client.execute(operation: "ListChannels", path: "/channels", httpMethod: .GET, serviceConfig: self.config, input: input, logger: logger, on: eventLoop) } /// Lists information about data set contents that have been created. public func listDatasetContents(_ input: ListDatasetContentsRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<ListDatasetContentsResponse> { return self.client.execute(operation: "ListDatasetContents", path: "/datasets/{datasetName}/contents", httpMethod: .GET, serviceConfig: self.config, input: input, logger: logger, on: eventLoop) } /// Retrieves information about data sets. public func listDatasets(_ input: ListDatasetsRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<ListDatasetsResponse> { return self.client.execute(operation: "ListDatasets", path: "/datasets", httpMethod: .GET, serviceConfig: self.config, input: input, logger: logger, on: eventLoop) } /// Retrieves a list of data stores. public func listDatastores(_ input: ListDatastoresRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<ListDatastoresResponse> { return self.client.execute(operation: "ListDatastores", path: "/datastores", httpMethod: .GET, serviceConfig: self.config, input: input, logger: logger, on: eventLoop) } /// Retrieves a list of pipelines. public func listPipelines(_ input: ListPipelinesRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<ListPipelinesResponse> { return self.client.execute(operation: "ListPipelines", path: "/pipelines", httpMethod: .GET, serviceConfig: self.config, input: input, logger: logger, on: eventLoop) } /// Lists the tags (metadata) which you have assigned to the resource. public func listTagsForResource(_ input: ListTagsForResourceRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<ListTagsForResourceResponse> { return self.client.execute(operation: "ListTagsForResource", path: "/tags", httpMethod: .GET, serviceConfig: self.config, input: input, logger: logger, on: eventLoop) } /// Sets or updates the AWS IoT Analytics logging options. Note that if you update the value of any loggingOptions field, it takes up to one minute for the change to take effect. Also, if you change the policy attached to the role you specified in the roleArn field (for example, to correct an invalid policy) it takes up to 5 minutes for that change to take effect. @discardableResult public func putLoggingOptions(_ input: PutLoggingOptionsRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<Void> { return self.client.execute(operation: "PutLoggingOptions", path: "/logging", httpMethod: .PUT, serviceConfig: self.config, input: input, logger: logger, on: eventLoop) } /// Simulates the results of running a pipeline activity on a message payload. public func runPipelineActivity(_ input: RunPipelineActivityRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<RunPipelineActivityResponse> { return self.client.execute(operation: "RunPipelineActivity", path: "/pipelineactivities/run", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop) } /// Retrieves a sample of messages from the specified channel ingested during the specified timeframe. Up to 10 messages can be retrieved. public func sampleChannelData(_ input: SampleChannelDataRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<SampleChannelDataResponse> { return self.client.execute(operation: "SampleChannelData", path: "/channels/{channelName}/sample", httpMethod: .GET, serviceConfig: self.config, input: input, logger: logger, on: eventLoop) } /// Starts the reprocessing of raw message data through the pipeline. public func startPipelineReprocessing(_ input: StartPipelineReprocessingRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<StartPipelineReprocessingResponse> { return self.client.execute(operation: "StartPipelineReprocessing", path: "/pipelines/{pipelineName}/reprocessing", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop) } /// Adds to or modifies the tags of the given resource. Tags are metadata which can be used to manage a resource. public func tagResource(_ input: TagResourceRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<TagResourceResponse> { return self.client.execute(operation: "TagResource", path: "/tags", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop) } /// Removes the given tags (metadata) from the resource. public func untagResource(_ input: UntagResourceRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<UntagResourceResponse> { return self.client.execute(operation: "UntagResource", path: "/tags", httpMethod: .DELETE, serviceConfig: self.config, input: input, logger: logger, on: eventLoop) } /// Updates the settings of a channel. @discardableResult public func updateChannel(_ input: UpdateChannelRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<Void> { return self.client.execute(operation: "UpdateChannel", path: "/channels/{channelName}", httpMethod: .PUT, serviceConfig: self.config, input: input, logger: logger, on: eventLoop) } /// Updates the settings of a data set. @discardableResult public func updateDataset(_ input: UpdateDatasetRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<Void> { return self.client.execute(operation: "UpdateDataset", path: "/datasets/{datasetName}", httpMethod: .PUT, serviceConfig: self.config, input: input, logger: logger, on: eventLoop) } /// Updates the settings of a data store. @discardableResult public func updateDatastore(_ input: UpdateDatastoreRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<Void> { return self.client.execute(operation: "UpdateDatastore", path: "/datastores/{datastoreName}", httpMethod: .PUT, serviceConfig: self.config, input: input, logger: logger, on: eventLoop) } /// Updates the settings of a pipeline. You must specify both a channel and a datastore activity and, optionally, as many as 23 additional activities in the pipelineActivities array. @discardableResult public func updatePipeline(_ input: UpdatePipelineRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<Void> { return self.client.execute(operation: "UpdatePipeline", path: "/pipelines/{pipelineName}", httpMethod: .PUT, serviceConfig: self.config, input: input, logger: logger, on: eventLoop) } } extension IoTAnalytics { /// Initializer required by `AWSService.with(middlewares:timeout:byteBufferAllocator:options)`. You are not able to use this initializer directly as there are no public /// initializers for `AWSServiceConfig.Patch`. Please use `AWSService.with(middlewares:timeout:byteBufferAllocator:options)` instead. public init(from: IoTAnalytics, patch: AWSServiceConfig.Patch) { self.client = from.client self.config = from.config.with(patch: patch) } }
apache-2.0
pauljohanneskraft/Algorithms-and-Data-structures
AlgorithmsDataStructures/Classes/Heaps & Trees/BinaryTree.swift
1
4596
// // BinaryTree.swift // Algorithms&DataStructures // // Created by Paul Kraft on 22.08.16. // Copyright © 2016 pauljohanneskraft. All rights reserved. // // swiftlint:disable trailing_whitespace public struct BinaryTree<Element: Equatable> { var root: Node? public let order: (Element, Element) -> Bool public init(order: @escaping (Element, Element) -> Bool) { self.order = order } } extension BinaryTree { final class Node { var data: Element var right: Node? var left: Node? let order: (Element, Element) -> Bool required init(data: Element, order: @escaping (Element, Element) -> Bool) { self.data = data self.order = order } } } extension BinaryTree: BinaryTreeProtocol, Tree { public func contains(_ data: Element) -> Bool { return root?.contains(data) ?? false } public mutating func insert(_ data: Element) throws { try push(data) } public mutating func remove(_ data: Element) throws { guard let res = try root?.remove(data) else { throw DataStructureError.notIn } root = res } public mutating func removeAll() { root = nil } public var count: UInt { return root?.count ?? 0 } public typealias DataElement = Element public var array: [Element] { get { return root?.array ?? [] } set { removeAll() newValue.forEach { try? insert($0) } } } public mutating func push(_ data: Element) throws { guard let root = root else { self.root = Node(data: data, order: order) return } try root.push(data) } public mutating func pop() -> Element? { var parent = root var current = root?.left guard current != nil else { let data = root?.data root = root?.right return data } while current?.left != nil { parent = current current = current?.left } let data = current?.data parent?.left = current?.right return data } } extension BinaryTree: CustomStringConvertible { public var description: String { let result = "\(BinaryTree<Element>.self)" guard let root = root else { return result + " empty." } return "\(result)\n" + root.description(depth: 1) } } extension BinaryTree.Node: BinaryTreeNodeProtocol { func push(_ newData: Element) throws { guard newData != data else { throw DataStructureError.alreadyIn } let newDataIsSmaller = order(newData, data) guard let node = newDataIsSmaller ? left: right else { if newDataIsSmaller { self.left = BinaryTree.Node(data: newData, order: order) } else { self.right = BinaryTree.Node(data: newData, order: order) } return } try node.push(newData) } func contains(_ data: Element) -> Bool { if self.data == data { return true } else if order(data, self.data) { return left?.contains(data) ?? false } else { return right?.contains(data) ?? true } } func removeLast() -> (data: Element, node: BinaryTree.Node?) { if let rightNode = right { let result = rightNode.removeLast() right = result.node return (result.data, self) } return (data: data, node: left) } func remove(_ data: Element) throws -> BinaryTree.Node? { if data == self.data { if let last = left?.removeLast() { left = last.node self.data = last.data return self } else { return right } } else if order(data, self.data) { left = try left?.remove(data) } else { right = try right?.remove(data) } return self } var count: UInt { return (left?.count ?? 0) + (right?.count ?? 0) + 1 } var array: [Element] { return (left?.array ?? []) + [data] + (right?.array ?? []) } } extension BinaryTree.Node { public func description(depth: UInt) -> String { let tab = " " var tabs = tab * depth var result = "\(tabs)∟\(data)\n" let d: UInt = depth + 1 tabs += tab result += left?.description(depth: d) ?? "" result += right?.description(depth: d) ?? "" return result } }
mit
kalanyuz/SwiftR
SwiftRDemo_macOS/Sources/ViewController.swift
1
3851
// // ViewController.swift // SMKTunes // // Created by Kalanyu Zintus-art on 10/21/15. // Copyright © 2015 Kalanyu. All rights reserved. // import Cocoa import SwiftR @IBDesignable class ViewController: NSViewController { @IBOutlet weak var graphView1: SRMergePlotView! { didSet { graphView1.title = "Filtered" graphView1.totalSecondsToDisplay = 10.0 } } @IBOutlet weak var graphView2: SRPlotView! { didSet { graphView2.title = "Split" graphView2.totalSecondsToDisplay = 10.0 } } @IBOutlet weak var graphView4: SRPlotView! { didSet { graphView4.title = "Split" } } @IBOutlet weak var graphView3: SRMergePlotView! { didSet { graphView3.title = "Raw" graphView3.totalSecondsToDisplay = 10.0 } } @IBOutlet weak var backgroundView: SRSplashBGView! { didSet { backgroundView.splashFill(toColor: NSColor(red: 241/255.0, green: 206/255.0, blue: 51/255.0, alpha: 1), .left) } } fileprivate let loadingView = SRSplashBGView(frame: CGRect.zero) fileprivate var loadingLabel = NSTextLabel(frame: CGRect.zero) fileprivate var loadingText = "Status : Now Loading.." { didSet { loadingLabel.stringValue = self.loadingText loadingLabel.sizeToFit() } } fileprivate let progressIndicator = NSProgressIndicator(frame: CGRect.zero) fileprivate var anotherDataTimer: Timer? var count = 0 fileprivate var fakeLoadTimer: Timer? fileprivate var samplingRate = 1000; override func viewDidLoad() { super.viewDidLoad() //prepare loading screen loadingView.frame = self.view.frame progressIndicator.frame = CGRect(origin: CGPoint(x: 50, y: 50), size: CGSize(width: 100, height: 100)) progressIndicator.style = .spinningStyle loadingLabel.frame = CGRect(origin: CGPoint(x: progressIndicator.frame.origin.x + progressIndicator.frame.width, y: 0), size: CGSize(width: 100, height: 100)) loadingLabel.stringValue = loadingText loadingLabel.font = NSFont.boldSystemFont(ofSize:15) loadingLabel.sizeToFit() loadingLabel.frame.origin.y = progressIndicator.frame.origin.y + (progressIndicator.frame.width/2) - (loadingLabel.frame.height/2) loadingLabel.lineBreakMode = .byTruncatingTail loadingView.addSubview(loadingLabel) loadingView.addSubview(progressIndicator) progressIndicator.startAnimation(nil) loadingView.wantsLayer = true loadingView.layer?.backgroundColor = NSColor.white.cgColor loadingView.autoresizingMask = [.viewHeightSizable, .viewWidthSizable] self.view.addSubview(loadingView) anotherDataTimer = Timer(timeInterval:1/60, target: self, selector: #selector(ViewController.addData), userInfo: nil, repeats: true) RunLoop.current.add(anotherDataTimer!, forMode: RunLoopMode.commonModes) fakeLoadTimer = Timer.scheduledTimer(withTimeInterval: 1.0, repeats: false, block: {x in self.systemStartup()}) graphView1.totalChannelsToDisplay = 6 graphView2.totalChannelsToDisplay = 6 graphView4.totalChannelsToDisplay = 6 graphView3.totalChannelsToDisplay = 6 } override func viewWillDisappear() { } func systemStartup() { loadingView.fade(toAlpha: 0) } func addData() { count += 1 let cgCount = sin(Double(count) * 1/60) graphView1.addData([cgCount, cgCount, cgCount, cgCount, cgCount , cgCount]) graphView2.addData([cgCount, cgCount, cgCount, cgCount, cgCount , cgCount]) graphView3.addData([cgCount, cgCount, cgCount, cgCount, cgCount , cgCount]) graphView4.addData([cgCount, cgCount, cgCount, cgCount, cgCount , cgCount]) } }
apache-2.0
DenisLitvin/Pinner
Pinner/Classes/CSMConstraintMaker.swift
1
4680
// // CSMConstraintManager.swift // // // Created by macbook on 28.10.2017. // Copyright © 2017 macbook. All rights reserved. // import UIKit public class CSMConstraintMaker { private var currentAnchorIdx = 0 private var anchors: [Any] = [] private var constraints: [NSLayoutConstraint] = [] fileprivate func add(_ anchor: Any){ anchors.append(anchor) } public func returnAll() -> [NSLayoutConstraint] { return constraints } public func deactivate(_ i: Int) { NSLayoutConstraint.deactivate([constraints[i]]) } public func deactivateAll() { NSLayoutConstraint.deactivate(constraints) } public func equal(_ constant: CGFloat) { _ = equalAndReturn(constant) } public func equalAndReturn(_ constant: CGFloat) -> NSLayoutConstraint { if let fromAnchor = anchors[currentAnchorIdx] as? NSLayoutDimension { constraints.append(fromAnchor.constraint(equalToConstant: constant)) } iterateConstraint() return constraints.last! } @discardableResult public func pin<T>(to anchor: NSLayoutAnchor<T>, const: CGFloat? = nil, mult: CGFloat? = nil, options: ConstraintOptions? = nil) -> NSLayoutConstraint { if let fromAnchor = anchors[currentAnchorIdx] as? NSLayoutDimension, let toAnchor = anchor as? NSLayoutDimension { constrainDimensions(fromAnchor: fromAnchor, toAnchor: toAnchor, const: const, mult: mult, options: options) } else if let fromAnchor = anchors[currentAnchorIdx] as? NSLayoutAnchor<T> { constrainAxes(fromAnchor: fromAnchor, toAnchor: anchor, const: const, options: options) } iterateConstraint() return constraints.last! } private func constrainAxes<T>(fromAnchor: NSLayoutAnchor<T>, toAnchor: NSLayoutAnchor<T>, const: CGFloat? = nil, options: ConstraintOptions? = nil){ switch options{ case .none, .some(.equal): constraints.append(fromAnchor.constraint(equalTo: toAnchor, constant: const ?? 0)) case .some(.lessOrEqual): constraints.append(fromAnchor.constraint(lessThanOrEqualTo: toAnchor, constant: const ?? 0)) case .some(.moreOrEqual): constraints.append(fromAnchor.constraint(greaterThanOrEqualTo: toAnchor, constant: const ?? 0)) } } private func constrainDimensions(fromAnchor: NSLayoutDimension, toAnchor: NSLayoutDimension, const: CGFloat? = nil, mult: CGFloat? = nil, options: ConstraintOptions? = nil){ switch options{ case .none, .some(.equal): constraints.append(fromAnchor.constraint(equalTo: toAnchor, multiplier: mult ?? 1, constant: const ?? 0)) case .some(.lessOrEqual): constraints.append(fromAnchor.constraint(lessThanOrEqualTo: toAnchor, multiplier: mult ?? 1, constant: const ?? 0)) case .some(.moreOrEqual): constraints.append(fromAnchor.constraint(greaterThanOrEqualTo: toAnchor, multiplier: mult ?? 1, constant: const ?? 0)) } } private func iterateConstraint(){ constraints.last?.isActive = true currentAnchorIdx += 1 } } public enum ConstraintOptions { case equal case lessOrEqual case moreOrEqual } public enum ConstraintType { case top case leading case left case bottom case trailing case right case height case width case centerX case centerY } extension UIView { public func makeConstraints(for constraints: ConstraintType..., closure: @escaping (ConstraintMaker) -> () ){ let maker = ConstraintMaker() translatesAutoresizingMaskIntoConstraints = false for constraint in constraints { switch constraint { case .top: maker.add(topAnchor) case .left: maker.add(leftAnchor) case.bottom: maker.add(bottomAnchor) case .right: maker.add(rightAnchor) case .leading: maker.add(leadingAnchor) case .trailing: maker.add(trailingAnchor) case .height: maker.add(heightAnchor) case .width: maker.add(widthAnchor) case .centerX: maker.add(centerXAnchor) case .centerY: maker.add(centerYAnchor) } } closure(maker) } }
mit
FuzzyHobbit/bitcoin-swift
BitcoinSwift/BigInteger+Operators.swift
2
1481
// // BigInteger+Operators.swift // BitcoinSwift // // Created by Kevin Greene on 11/29/14. // Copyright (c) 2014 DoubleSha. All rights reserved. // public func ==(left: BigInteger, right: BigInteger) -> Bool { return left.isEqual(right) } public func <(left: BigInteger, right: BigInteger) -> Bool { return left.lessThan(right) } public func <=(left: BigInteger, right: BigInteger) -> Bool { return left.lessThanOrEqual(right) } public func >(left: BigInteger, right: BigInteger) -> Bool { return left.greaterThan(right) } public func >=(left: BigInteger, right: BigInteger) -> Bool { return left.greaterThanOrEqual(right) } public func +(left: BigInteger, right: BigInteger) -> BigInteger { return left.add(right) } public func -(left: BigInteger, right: BigInteger) -> BigInteger { return left.subtract(right) } public func *(left: BigInteger, right: BigInteger) -> BigInteger { return left.multiply(right) } public func /(left: BigInteger, right: BigInteger) -> BigInteger { return left.divide(right) } public func %(left: BigInteger, right: BigInteger) -> BigInteger { return left.modulo(right) } public func <<(left: BigInteger, right: Int) -> BigInteger { return left.shiftLeft(Int32(right)) } public func >>(left: BigInteger, right: Int) -> BigInteger { return left.shiftRight(Int32(right)) } // TODO: Make this conform to IntegerArithmeticType? BitwiseOperationsType? extension BigInteger: Comparable, IntegerLiteralConvertible {}
apache-2.0
garygriswold/Bible.js
SafeBible2/SafeBible_ios/SafeBible/ViewControllers/NotesListViewController.swift
1
5966
// // NotesListViewController.swift // Settings // // Created by Gary Griswold on 12/17/18. // Copyright © 2018 ShortSands. All rights reserved. // import UIKit import WebKit class NotesListViewController : AppTableViewController, UITableViewDataSource { static func push(controller: UIViewController?) { let notesListViewController = NotesListViewController() controller?.navigationController?.pushViewController(notesListViewController, animated: true) } private var reference: Reference! private var notes: [Note]! private var toolBar: NotesListToolbar! deinit { print("**** deinit NotesListViewController ******") } override func loadView() { super.loadView() self.reference = HistoryModel.shared.current() self.toolBar = NotesListToolbar(book: reference.book!, controller: self) let notes = NSLocalizedString("Notes", comment: "Notes list view page title") self.navigationItem.title = (self.reference.book?.name ?? "") + " " + notes self.tableView.rowHeight = UITableView.automaticDimension; self.tableView.estimatedRowHeight = 50.0; // set to whatever your "average" cell height i self.tableView.register(NoteCell.self, forCellReuseIdentifier: "notesCell") self.tableView.dataSource = self } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) self.navigationController?.isToolbarHidden = false self.notes = NotesDB.shared.getNotes(bookId: reference.bookId, note: true, lite: true, book: true) self.tableView.reloadData() } // This method is called by NotesListToolbar, when user changes what is to be included func refresh(note: Bool, lite: Bool, book: Bool) { self.notes = NotesDB.shared.getNotes(bookId: reference.bookId, note: note, lite: lite, book: book) self.tableView.reloadData() } // // Data Source // func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return self.notes.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let note = self.notes[indexPath.row] let noteRef = note.getReference() let cell = tableView.dequeueReusableCell(withIdentifier: "notesCell", for: indexPath) as? NoteCell guard cell != nil else { fatalError("notesCell must be type NotesCell") } cell!.backgroundColor = AppFont.backgroundColor cell!.passage.font = AppFont.sansSerif(style: .subheadline) cell!.passage.textColor = AppFont.textColor cell!.passage.text = noteRef.description(startVerse: note.startVerse, endVerse: note.endVerse) + " (\(noteRef.bibleName))" cell!.noteText.numberOfLines = 10 cell!.noteText.font = AppFont.sansSerif(style: .body) cell!.noteText.textColor = AppFont.textColor if note.highlight != nil { cell!.iconGlyph.text = Note.liteIcon//"\u{1F58C}"// "\u{1F3F7}" cell!.iconGlyph.backgroundColor = ColorPicker.toUIColor(hexColor: note.highlight!) cell!.noteText.text = note.text cell!.accessoryType = .none } else if note.bookmark { cell!.iconGlyph.text = Note.bookIcon//"\u{1F516}" cell!.iconGlyph.backgroundColor = AppFont.backgroundColor cell!.noteText.text = nil cell!.accessoryType = .none } else if note.note { cell!.iconGlyph.text = Note.noteIcon//"\u{1F5D2}" cell?.iconGlyph.backgroundColor = AppFont.backgroundColor cell!.noteText.text = note.text cell!.accessoryType = .disclosureIndicator } cell!.selectionStyle = .default return cell! } // Return true for each row that can be edited func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool { return true } // Commit data row change to the data source func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) { if editingStyle == .delete { let note = self.notes[indexPath.row] self.notes.remove(at: indexPath.row) NotesDB.shared.deleteNote(noteId: note.noteId) tableView.deleteRows(at: [indexPath], with: UITableView.RowAnimation.automatic) // Remove Note from current pages if present. ReaderViewQueue.shared.reloadIfActive(reference: note.getReference()) } } // // Delegate // func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { tableView.deselectRow(at: indexPath, animated: true) let note = self.notes[indexPath.row] if note.note { NoteEditViewController.push(note: note, controller: self) } else { let ref = HistoryModel.shared.current() if note.bibleId != ref.bibleId || note.bookId != ref.bookId || note.chapter != ref.chapter { let noteRef = note.getReference() if let book = noteRef.book { HistoryModel.shared.changeReference(bookId: book.bookId, chapter: noteRef.chapter) NotificationCenter.default.post(name: ReaderPagesController.NEW_REFERENCE, object: HistoryModel.shared.current()) } } self.navigationController?.popToRootViewController(animated: true) } } // Identifies Add and Delete Rows func tableView(_ tableView: UITableView, editingStyleForRowAt: IndexPath) -> UITableViewCell.EditingStyle { return UITableViewCell.EditingStyle.delete } }
mit