repo_name
stringlengths 6
91
| path
stringlengths 8
968
| copies
stringclasses 210
values | size
stringlengths 2
7
| content
stringlengths 61
1.01M
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 6
99.8
| line_max
int64 12
1k
| alpha_frac
float64 0.3
0.91
| ratio
float64 2
9.89
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
MarcoSantarossa/SwiftyToggler | Source/FeaturesList/Coordinator/FeaturesListCoordinator.swift | 1 | 2952 | //
// FeaturesListCoordinator.swift
//
// Copyright (c) 2017 Marco Santarossa (https://marcosantadev.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.
//
protocol FeaturesListCoordinatorProtocol {
func start(presentingMode: PresentingMode) throws
}
final class FeaturesListCoordinator: FeaturesListCoordinatorProtocol {
fileprivate(set) var window: UIWindowProtocol?
func start(presentingMode: PresentingMode) throws {
switch presentingMode {
case .modal(let parentWindow):
try presentModal(in: parentWindow)
case .inParent(let parentViewController, let parentView):
presentIn(parentViewController, parentView: parentView)
}
}
private func presentModal(in parentWindow: UIWindowProtocol) throws {
guard self.window == nil else {
throw SwiftyTogglerError.modalFeaturesListAlreadyPresented
}
parentWindow.rootViewControllerType = createFeaturestListViewController(presentingMode: .modal(parentWindow))
parentWindow.makeKeyAndVisible()
parentWindow.backgroundColor = .white
self.window = parentWindow
}
private func createFeaturestListViewController(presentingMode: PresentingMode) -> FeaturesListViewController {
let viewModel = FeaturesListViewModel(presentingMode: presentingMode)
viewModel.delegate = self
return FeaturesListViewController(viewModel: viewModel)
}
private func presentIn(_ parentViewController: UIViewControllerProtocol, parentView: UIViewProtocol?) {
let viewController = createFeaturestListViewController(presentingMode: .inParent(parentViewController, parentView))
parentViewController.addFillerChildViewController(viewController, toView: parentView)
}
}
extension FeaturesListCoordinator: FeaturesListViewModelDelegate {
func featuresListViewModelNeedsClose() {
destroyWindow()
}
private func destroyWindow() {
window?.isHidden = true
window?.rootViewControllerType = nil
window = nil
}
}
| mit | a08ef3a0881fb006cdda7472fd87a296 | 38.891892 | 123 | 0.782182 | 4.569659 | false | false | false | false |
djabo/DataCache | DataCache.swift | 1 | 1911 | //
// DataCache.swift
//
import UIKit
import ImageIO
protocol Datable {
init?(data: NSData)
func toData() -> NSData
}
extension UIImage: Datable {
func toData() -> NSData {
return UIImagePNGRepresentation(self)
}
}
class DataCache<T: Datable> {
private let queue = NSOperationQueue()
private let cache = LRUCache<NSURL, T>(maxSize: 100)
var count: Int { return self.cache.count }
init() {
self.queue.name = "DataCacheQueue"
self.queue.maxConcurrentOperationCount = 10;
}
func clear() {
self.cache.clear()
}
subscript (url: NSURL) -> T? {
get {
if let data = NSData(contentsOfURL: url) {
if let datable = T(data: data) {
self.cache[url] = datable
return datable
}
}
return nil
}
}
func containsKey(key: NSURL) -> Bool {
return self.cache.containsKey(key)
}
func objectForURL(url: NSURL, block: ((url: NSURL, object: T) -> Void)?) -> T? {
if let cachedImage = self.cache[url] {
return cachedImage
} else {
self.queue.addOperationWithBlock() {
if let data = NSData(contentsOfURL: url) {
if data.length > 0 {
if let datable = T(data: data) {
datable.toData()
self.cache[url] = datable
if block != nil {
NSOperationQueue.mainQueue().addOperationWithBlock() {
block!(url: url, object: datable)
}
}
}
}
}
}
return nil
}
}
}
| mit | 338ef2d1a00072c7e8b565a326c80413 | 25.541667 | 86 | 0.44741 | 4.9 | false | false | false | false |
ccrama/Slide-iOS | Slide for Apple Watch Extension/SubmissionRowController.swift | 1 | 12062 | //
// SubmissionRowController.swift
// Slide for Apple Watch Extension
//
// Created by Carlos Crane on 9/23/18.
// Copyright © 2018 Haptic Apps. All rights reserved.
//
import CoreGraphics
import Foundation
import UIKit
import WatchKit
public class SubmissionRowController: NSObject {
var titleText: NSAttributedString?
var thumbnail: UIImage?
var largeimage: UIImage?
var id: String?
var sub: String?
var scoreText: String!
var commentText: String!
var dictionary: NSDictionary!
@IBOutlet weak var imageGroup: WKInterfaceGroup!
@IBOutlet var bannerImage: WKInterfaceImage!
@IBOutlet weak var scoreLabel: WKInterfaceLabel!
@IBOutlet weak var commentsLabel: WKInterfaceLabel!
@IBOutlet weak var infoLabel: WKInterfaceLabel!
@IBOutlet weak var titleLabel: WKInterfaceLabel!
@IBOutlet var bigImage: WKInterfaceImage!
@IBOutlet var thumbGroup: WKInterfaceGroup!
@IBOutlet var upvote: WKInterfaceButton!
@IBOutlet var downvote: WKInterfaceButton!
@IBOutlet var readlater: WKInterfaceButton!
@IBAction func didUpvote() {
(WKExtension.shared().visibleInterfaceController as? Votable)?.sharedUp = upvote
(WKExtension.shared().visibleInterfaceController as? Votable)?.sharedDown = downvote
(WKExtension.shared().visibleInterfaceController as? Votable)?.doVote(id: id!, upvote: true, downvote: false)
}
@IBAction func didDownvote() {
(WKExtension.shared().visibleInterfaceController as? Votable)?.sharedUp = upvote
(WKExtension.shared().visibleInterfaceController as? Votable)?.sharedDown = downvote
(WKExtension.shared().visibleInterfaceController as? Votable)?.doVote(id: id!, upvote: false, downvote: true)
}
@IBAction func didSaveLater() {
(WKExtension.shared().visibleInterfaceController as? Votable)?.sharedReadLater = readlater
(WKExtension.shared().visibleInterfaceController as? Votable)?.doReadLater(id: id!, sub: sub!)
}
func setData(dictionary: NSDictionary, color: UIColor) {
largeimage = nil
thumbnail = nil
self.dictionary = dictionary
let titleFont = UIFont.systemFont(ofSize: 14)
let subtitleFont = UIFont.boldSystemFont(ofSize: 10)
let attributedTitle = NSMutableAttributedString(string: dictionary["title"] as! String, attributes: [NSAttributedString.Key.font: titleFont, NSAttributedString.Key.foregroundColor: UIColor.white])
id = dictionary["id"] as? String ?? ""
sub = dictionary["subreddit"] as? String ?? ""
let nsfw = NSMutableAttributedString.init(string: "\u{00A0}NSFW\u{00A0}", attributes: [NSAttributedString.Key.foregroundColor: UIColor.red, NSAttributedString.Key.font: subtitleFont])
let spoiler = NSMutableAttributedString.init(string: "\u{00A0}SPOILER\u{00A0}", attributes: [NSAttributedString.Key.foregroundColor: UIColor.gray, NSAttributedString.Key.font: subtitleFont])
let spacer = NSMutableAttributedString.init(string: " ")
if let flair = dictionary["link_flair_text"] as? String {
attributedTitle.append(spacer)
attributedTitle.append(NSMutableAttributedString.init(string: "\u{00A0}\(flair)\u{00A0}", attributes: [NSAttributedString.Key.foregroundColor: UIColor.gray, NSAttributedString.Key.font: subtitleFont]))
}
if let isNsfw = dictionary["nsfw"] as? Bool, isNsfw == true {
attributedTitle.append(spacer)
attributedTitle.append(nsfw)
}
if let nsfw = dictionary["spoiler"] as? Bool, nsfw == true {
attributedTitle.append(spacer)
attributedTitle.append(spoiler)
}
let attrs = [NSAttributedString.Key.font: subtitleFont, NSAttributedString.Key.foregroundColor: UIColor.white]
let endString = NSMutableAttributedString(string: " • \(dictionary["created"] as! String)", attributes: [NSAttributedString.Key.font: subtitleFont, NSAttributedString.Key.foregroundColor: UIColor.gray])
let authorString = NSMutableAttributedString(string: "\nu/\(dictionary["author"] as? String ?? "")", attributes: [NSAttributedString.Key.font: subtitleFont, NSAttributedString.Key.foregroundColor: UIColor.gray])
endString.append(authorString)
// if SettingValues.domainInInfo && !full {
// endString.append(NSAttributedString.init(string: " • \(submission.domain)", attributes: [NSFontAttributeName: FontGenerator.fontOfSize(size: 12, submission: true), NSForegroundColorAttributeName: colorF]))
// }
//
// let tag = ColorUtil.getTagForUser(name: submission.author)
// if !tag.isEmpty {
// let tagString = NSMutableAttributedString(string: "\u{00A0}\(tag)\u{00A0}", attributes: [NSFontAttributeName: FontGenerator.boldFontOfSize(size: 12, submission: false), NSForegroundColorAttributeName: colorF])
// tagString.addAttributes([kTTTBackgroundFillColorAttributeName: UIColor(rgb: 0x2196f3), NSFontAttributeName: FontGenerator.boldFontOfSize(size: 12, submission: false), NSForegroundColorAttributeName: UIColor.white, kTTTBackgroundFillPaddingAttributeName: UIEdgeInsets.init(top: 1, left: 1, bottom: 1, right: 1), kTTTBackgroundCornerRadiusAttributeName: 3], range: NSRange.init(location: 0, length: tagString.length))
// endString.append(spacer)
// endString.append(tagString)
// }
//
let boldString = NSMutableAttributedString(string: "r/\(dictionary["subreddit"] ?? "")", attributes: attrs)
boldString.addAttribute(NSAttributedString.Key.foregroundColor, value: color, range: NSRange.init(location: 0, length: boldString.length))
let infoString = NSMutableAttributedString()
infoString.append(boldString)
infoString.append(endString)
infoString.append(NSAttributedString(string: "\n"))
infoString.append(attributedTitle)
titleLabel.setAttributedText(infoString)
let type = ContentType.getContentType(dict: dictionary)
var big = false
var text = ""
switch type {
case .ALBUM:
text = ("Album")
case .REDDIT_GALLERY:
text = ("Reddit Gallery")
case .EXTERNAL:
text = "External Link"
case .LINK, .EMBEDDED, .NONE:
text = "Link"
case .DEVIANTART:
text = "Deviantart"
case .TUMBLR:
text = "Tumblr"
case .XKCD:
text = ("XKCD")
case .GIF:
if (dictionary["domain"] as? String ?? "") == "v.redd.it" {
text = "Reddit Video"
} else {
text = ("GIF")
}
case .IMGUR, .IMAGE:
big = true && dictionary["bigimage"] != nil
text = ("Image")
case .YOUTUBE:
text = "YouTube"
case .STREAMABLE:
text = "Streamable"
case .VID_ME:
text = ("Vid.me")
case .REDDIT:
text = ("Reddit content")
default:
text = "Link"
}
readlater.setBackgroundColor((dictionary["readLater"] ?? false) as! Bool ? UIColor.init(hexString: "#4CAF50") : UIColor.gray)
upvote.setBackgroundColor((dictionary["upvoted"] ?? false) as! Bool ? UIColor.init(hexString: "#FF5700") : UIColor.gray)
downvote.setBackgroundColor((dictionary["downvoted"] ?? false) as! Bool ? UIColor.init(hexString: "#9494FF") : UIColor.gray)
readlater.setBackgroundColor(UIColor.gray)
if big {
bigImage.setHidden(false)
thumbGroup.setHidden(true)
} else {
bigImage.setHidden(true)
thumbGroup.setHidden(false)
}
let domain = dictionary["domain"] as? String ?? ""
let aboutString = NSMutableAttributedString(string: "\(text)", attributes: [NSAttributedString.Key.font: subtitleFont.withSize(13)])
aboutString.append(NSMutableAttributedString(string: "\n\(domain)", attributes: [NSAttributedString.Key.font: subtitleFont]))
infoLabel.setAttributedText(aboutString)
// infoString.append(NSAttributedString.init(string: "\n"))
// var sColor = UIColor.white
// switch ActionStates.getVoteDirection(s: submission) {
// case .down:
// sColor = ColorUtil.downvoteColor
// case .up:
// sColor = ColorUtil.upvoteColor
// case .none:
// break
// }
//
// let subScore = NSMutableAttributedString(string: (submission.score >= 10000 && SettingValues.abbreviateScores) ? String(format: " %0.1fk points", (Double(submission.score) / Double(1000))) : " \(submission.score) points", attributes: [NSFontAttributeName: FontGenerator.boldFontOfSize(size: 12, submission: false), NSForegroundColorAttributeName: sColor])
//
// infoString.append(subScore)
//
// if SettingValues.scoreInTitle {
// infoString.append(spacer)
// }
// let scoreString = NSMutableAttributedString(string: "\(submission.commentCount) comments", attributes: [NSFontAttributeName: FontGenerator.boldFontOfSize(size: 12, submission: false), NSForegroundColorAttributeName: colorF])
// infoString.append(scoreString)
titleText = infoString
let scoreNumber = dictionary["score"] as? Int ?? 0
scoreText = scoreNumber > 1000 ?
String(format: "%0.1fk ", (Double(scoreNumber) / Double(1000))) : "\(scoreNumber) "
scoreLabel.setText(scoreText)
commentText = "\(dictionary["num_comments"] as? Int ?? 0)"
commentsLabel.setText(commentText)
if big, let imageurl = (dictionary["bigimage"] as? String), !imageurl.isEmpty(), imageurl.startsWith("http") {
DispatchQueue.global().async {
let imageUrl = URL(string: imageurl)!
URLSession.shared.dataTask(with: imageUrl, completionHandler: { (data, _, _) in
if let image = UIImage(data: data!) {
self.largeimage = image
DispatchQueue.main.async {
self.bigImage.setImage(self.largeimage!)
}
} else {
NSLog("could not load data from image URL: \(imageUrl)")
}
}).resume()
}
} else if let thumburl = (dictionary["thumbnail"] as? String), !thumburl.isEmpty(), thumburl.startsWith("http") {
DispatchQueue.global().async {
let imageUrl = URL(string: thumburl)!
URLSession.shared.dataTask(with: imageUrl, completionHandler: { (data, _, _) in
if let image = UIImage(data: data!) {
self.thumbnail = image
DispatchQueue.main.async {
self.bannerImage.setImage(self.thumbnail!)
}
} else {
NSLog("could not load data from image URL: \(imageUrl)")
}
}).resume()
}
} else if type == .SELF || type == .NONE {
thumbGroup.setHidden(true)
bigImage.setHidden(true)
} else {
if dictionary["spoiler"] as? Bool ?? false {
self.bannerImage.setImage(UIImage(named: "reports")?.getCopy(withSize: CGSize(width: 25, height: 25)))
} else if type == .REDDIT || (dictionary["is_self"] as? Bool ?? false) {
self.bannerImage.setImage(UIImage(named: "reddit")?.getCopy(withSize: CGSize(width: 25, height: 25)))
} else {
self.bannerImage.setImage(UIImage(named: "nav")?.getCopy(withSize: CGSize(width: 25, height: 25)))
}
}
self.imageGroup.setCornerRadius(10)
}
}
| apache-2.0 | cd94a707cdbb6d7b5a3253f3ed5d417c | 48.822314 | 429 | 0.623704 | 4.765613 | false | false | false | false |
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 | b44c81c3710665cee67fa116ae6bbd20 | 31.736842 | 116 | 0.656592 | 5.334477 | false | false | false | false |
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 | 163563b449510a3c727a319fa0fdfb4e | 29.86 | 99 | 0.686973 | 4.136729 | false | false | false | false |
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 | b30bd0541d983ec4167638db00adb403 | 22.678571 | 81 | 0.662142 | 4.25 | false | false | false | false |
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 | bc41554f7e8e7e9d46f6224b6e17656a | 27.31746 | 82 | 0.633969 | 4.682415 | false | false | false | false |
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 | a1f5ecd11e447f357f1a23e08af50834 | 35.802326 | 152 | 0.559242 | 4.741573 | false | false | false | false |
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 | fa1455e7bcb9c156d2e08f6c68f1b16d | 26.190476 | 130 | 0.589609 | 4.336709 | false | false | false | false |
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 | 9e187522cc76a69c195d7737957fa4e9 | 23.392638 | 114 | 0.649899 | 4.91471 | false | false | false | false |
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 | 08de716891065a45627207ed0737ebe1 | 28.84127 | 111 | 0.63883 | 5.749235 | false | false | false | false |
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 | 221c84b77e195eec1840da952f454de9 | 28.288889 | 67 | 0.567957 | 4.65371 | false | false | false | false |
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 | 1272a9b36d38909514ddc607858f860c | 33.727811 | 167 | 0.618674 | 4.940236 | false | false | false | false |
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 | c70a8b74609447c3ff53701e85836747 | 74.992057 | 242 | 0.67938 | 3.287089 | false | false | false | false |
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 | 263acf0c57b737a42c22dd3273d4feb1 | 30.871854 | 351 | 0.674253 | 4.366144 | false | false | false | false |
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 | 0a389b7009dbf124eb421beed0476fc1 | 42.025424 | 167 | 0.688202 | 4.948343 | false | false | false | false |
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 | 97fccfc199d23b6aa6f685d01fcc503a | 18.066667 | 69 | 0.45035 | 3.548387 | false | false | false | false |
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 | e6e9aaaa97fa57cab081be50e29d6405 | 30.75463 | 253 | 0.534918 | 4.789804 | false | false | false | false |
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 | 3b558dc624a3b6226ed2dae649519a0b | 31.26087 | 110 | 0.568134 | 4.950334 | false | false | false | false |
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 | a9a4baa6938c480e9d3b2c2a51213b50 | 35.725564 | 207 | 0.658374 | 5.248791 | false | false | false | false |
longitachi/ZLPhotoBrowser | Sources/General/ZLProgressView.swift | 1 | 2377 | //
// ZLProgressView.swift
// ZLPhotoBrowser
//
// Created by long on 2020/8/13.
//
// Copyright (c) 2020 Long Zhang <[email protected]>
//
// 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 | 220e1583a499f6c1ba606a2db78bc297 | 34.477612 | 122 | 0.665124 | 4.35348 | false | false | false | false |
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 | 520cf36eb7551e2207d4fc0b29ba3c41 | 29.223881 | 122 | 0.799012 | 5.688202 | false | true | false | false |
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 | 0ee1a35ee2b38b00dacfb231b0bd86d3 | 25.5 | 124 | 0.63522 | 4.025316 | false | false | false | false |
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 | b0f6baed25e84d7593ccf88e0b062ea9 | 25.036364 | 115 | 0.597067 | 4.546032 | false | false | false | false |
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 | 315f6511a990fbf087f4f6796778f948 | 28.559585 | 155 | 0.643996 | 5.210046 | false | false | false | false |
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 | 506f9196c519653e43f260b90c8a3a2b | 17.915254 | 80 | 0.526882 | 2.583333 | false | false | false | false |
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 | 1001846592a3e6a278058d43cede720a | 43.74537 | 116 | 0.765028 | 4.694026 | false | false | false | false |
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 | cbc5f92b467453ba50a41557eb13ca5b | 29.612022 | 192 | 0.620314 | 3.124373 | false | false | false | false |
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 | ea7f90f3d6f23adf9f3b97395d885b7f | 34.444444 | 430 | 0.667712 | 3.238579 | false | false | false | false |
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 | fad9a5285606f5d9dd66df8bf5230d6c | 32.422619 | 145 | 0.682458 | 4.572476 | false | false | false | false |
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 | c3fabf9cffe810b011e27d7d3df5b3a5 | 46.517241 | 241 | 0.603048 | 4.631933 | false | false | false | false |
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 | 0f755f736dee104e46f1b67765c789bd | 20.121212 | 55 | 0.632712 | 3.893855 | false | false | false | false |
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 | 564a95866e424fcce8b392811ef2eaea | 34.316901 | 97 | 0.488136 | 5.445168 | false | false | false | false |
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 | 191e453f80aa9037774f21186251fabc | 19.862069 | 74 | 0.647107 | 2.99505 | false | false | false | false |
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 | a39b0ef6f466021fa1e361b9828b51d8 | 32.670213 | 113 | 0.682464 | 5.180033 | false | false | false | false |
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 | b367430a09c448adb53a982fcfaf8bd4 | 42.132813 | 201 | 0.613713 | 5.875998 | false | false | false | false |
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 | 93f841e3b327bbdc52591c6d136db8da | 20.733333 | 92 | 0.559816 | 4.346667 | false | false | false | false |
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 | 8e300fccf5f19c48aa5477f90c9a27cb | 49.349515 | 290 | 0.697069 | 5.447479 | false | false | false | false |
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 | ad181fd56b9b342bf160be5271df392b | 26.428571 | 92 | 0.692708 | 3.938462 | false | false | false | false |
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 | 057c8582fa80082f5ff8f88308289241 | 41.19337 | 129 | 0.71206 | 7.776986 | false | false | false | false |
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 | 287b05e26efcf2dfb6ce60f15089ed9a | 25.354167 | 140 | 0.585771 | 4.080645 | false | false | false | false |
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 | 1711ab8bb96cd151af65aef1ed900710 | 27.035714 | 92 | 0.712102 | 4.131579 | false | false | false | false |
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 | da1fdca0d5fcac3ff90552f30530a06f | 30.034483 | 123 | 0.751481 | 5.075188 | false | false | false | false |
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 | 00e0f2f5542d4c8d0a6d75788c8bf61e | 25.816327 | 105 | 0.707002 | 4.692857 | false | false | false | false |
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 | 551c8470938b8ec3f53b5c41f6b83221 | 27.761364 | 109 | 0.656262 | 4.972495 | false | false | false | false |
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 | 9a84f224651bc7dcb28054d15faa7f3c | 37.087838 | 119 | 0.562001 | 4.6975 | false | false | false | false |
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 | 98f61fb6d5126c5dfec78991d1c24d8e | 22.740741 | 79 | 0.694228 | 3.237374 | false | false | false | false |
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 | 355907d0f38efd3dcf1e86107bbeb8b9 | 35.613953 | 157 | 0.616997 | 5.586941 | false | false | false | false |
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 | 05a6b7b1511cece42143ae7a90858516 | 28.880597 | 96 | 0.534466 | 5.094148 | false | false | false | false |
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 | fbf278b8b8d4825413e2bb1503d0edc6 | 36.606299 | 96 | 0.661034 | 4.614716 | false | false | false | false |
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 | eb3635309f4d7f61f379aa482ca31fbb | 27.597484 | 111 | 0.597867 | 5.719497 | false | false | false | false |
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 | 98e30ed3bf4aef7bd28e1394573d5bc0 | 26.631579 | 201 | 0.625905 | 5.585106 | false | false | false | false |
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 | cc5044a2ac2b89d1202b5614fb5d541d | 32.173913 | 136 | 0.64941 | 4.798742 | false | false | false | false |
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 | 9d021ef304da860e85c7d44679571d6a | 50.92132 | 202 | 0.60918 | 5.279226 | false | false | false | false |
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 | 24d61529308eb2d69d23213f75c19aef | 24.098361 | 83 | 0.541258 | 4.206044 | false | false | false | false |
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 | c618896f0040a0412b2d8bfed14663d7 | 30.300813 | 166 | 0.676364 | 4.235424 | false | false | false | false |
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 | 3f56af5524186021717b6cf0f83963e8 | 30.829932 | 177 | 0.605471 | 5.004278 | false | false | false | false |
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 | 77b3f4f439754cba695f82ab429641e1 | 40.137931 | 111 | 0.636379 | 4.760575 | false | false | false | false |
GhostSK/SpriteKitPractice | FightSceneDemo/FightSceneDemo/MagicBaseModel.swift | 1 | 1129 | //
// MagicBaseModel.swift
// FightSceneDemo
//
// Created by 胡杨林 on 17/3/7.
// Copyright © 2017年 胡杨林. All rights reserved.
//
import Foundation
class MagicBaseModel: NSObject {
public var MagicName:String? = nil
public var MagicCategory:String? = nil //单体/群体/辅助/dot/虚弱/加速等分类
public var MagicTargets:[UnitNode]? = nil //作用对象,可能为群体
public var Buff1:String? = nil //持续效果1
public var Buff1KeepTime:NSInteger = 0 //buff1持续时间
public var buff2:String? = nil
public var buff2KeepTime:NSInteger = 0
public var buff3:String? = nil
public var buff3KeepTime:NSInteger = 0
public var directEffectValue:NSInteger = 0 //翔舞首跳/直接效果
public var indirectEffectValue:NSInteger = 0 //翔舞每一跳
public var endEffectValue:NSInteger = 0 //上元结束跳
init(Name:String, MagicCategory:String, directEffect:NSInteger) {
super.init()
self.MagicName = Name
self.MagicCategory = MagicCategory
self.directEffectValue = directEffect
}
}
| apache-2.0 | 693e7d022c9c50cf8655a9f00e4dca51 | 28.882353 | 69 | 0.679134 | 3.342105 | false | false | false | false |
mvader/advent-of-code | 2021/08/02.swift | 1 | 1766 | import Foundation
extension StringProtocol {
subscript(offset: Int) -> Character {
self[index(startIndex, offsetBy: offset)]
}
}
struct Entry {
let patterns: [String]
let output: [String]
init(_ raw: String) {
let parts = raw.components(separatedBy: " | ")
patterns = parts.first!.split(separator: " ").map { String($0) }
output = parts.last!.split(separator: " ").map { String($0) }
}
func guessDigits() throws -> [String: Int] {
let one = patterns.filter { $0.count == 2 }.first!
let four = patterns.filter { $0.count == 4 }.first!
let patterns = [String: Int](uniqueKeysWithValues: try patterns.map { p in
let pattern = String(p.sorted())
switch p.count {
case 2: return (pattern, 1)
case 3: return (pattern, 7)
case 4: return (pattern, 4)
case 7: return (pattern, 8)
case 5:
if one.allSatisfy({ pattern.contains($0) }) {
return (pattern, 3)
}
if four.filter({ pattern.contains($0) }).count == 3 {
return (pattern, 5)
}
return (pattern, 2)
case 6:
if four.allSatisfy({ pattern.contains($0) }) {
return (pattern, 9)
}
if one.allSatisfy({ pattern.contains($0) }) {
return (pattern, 0)
}
return (pattern, 6)
default:
throw GuessError.invalidPattern
}
})
return patterns
}
func decode() throws -> Int {
let digits = try guessDigits()
return Int(output.reduce("") { acc, e in acc + String(digits[String(e.sorted())]!) })!
}
}
enum GuessError: Error {
case invalidPattern
}
let entries = try String(contentsOfFile: "./input.txt", encoding: .utf8)
.split(separator: "\n")
.map { line in Entry(String(line)) }
let targetDigits = [2, 3, 4, 7]
let result = try entries.reduce(0) { acc, e in acc + (try e.decode()) }
print(result)
| mit | f894790901951ff43e83ab3a0d045597 | 22.864865 | 88 | 0.625142 | 3.087413 | false | false | false | false |
ewanmellor/KZLinkedConsole | KZLinkedConsole/Extensions/NSTextView+Extensions.swift | 1 | 4566 | //
// Created by Krzysztof Zabłocki on 05/12/15.
// Copyright (c) 2015 pixle. All rights reserved.
//
import Foundation
import AppKit
extension NSTextView {
func kz_mouseDown(event: NSEvent) {
let pos = convertPoint(event.locationInWindow, fromView:nil)
let idx = characterIndexForInsertionAtPoint(pos)
guard let expectedClass = NSClassFromString("IDEConsoleTextView")
where isKindOfClass(expectedClass) && attributedString().length > 1 && idx < attributedString().length else {
kz_mouseDown(event)
return
}
let attr = attributedString().attributesAtIndex(idx, effectiveRange: nil)
guard let fileName = attr[KZLinkedConsole.Strings.linkedFileName] as? String,
let lineNumber = attr[KZLinkedConsole.Strings.linkedLine] as? String,
let appDelegate = NSApplication.sharedApplication().delegate else {
kz_mouseDown(event)
return
}
guard let workspacePath = KZPluginHelper.workspacePath() else {
return
}
guard let filePath = kz_findFile(workspacePath, fileName) else {
return
}
if appDelegate.application!(NSApplication.sharedApplication(), openFile: filePath) {
dispatch_async(dispatch_get_main_queue()) {
if let textView = KZPluginHelper.editorTextView(inWindow: self.window),
let line = Int(lineNumber) where line >= 1 {
self.scrollTextView(textView, toLine:line)
}
}
}
}
private func scrollTextView(textView: NSTextView, toLine line: Int) {
guard let text = (textView.string as NSString?) else {
return
}
var currentLine = 1
var index = 0
for (; index < text.length; currentLine++) {
let lineRange = text.lineRangeForRange(NSMakeRange(index, 0))
index = NSMaxRange(lineRange)
if currentLine == line {
textView.scrollRangeToVisible(lineRange)
textView.setSelectedRange(lineRange)
break
}
}
}
}
/**
[workspacePath : [fileName : filePath]]
*/
var kz_filePathCache = [String : [String : String]]()
/**
Search for the given filename in the given workspace.
To avoid parsing the project's header file inclusion path,
we use the following heuristic:
1. Look in kz_filePathCache.
2. Look for the file in the current workspace.
3. Look in the parent directory of the current workspace,
excluding the current workspace because we've already searched there.
4. Keep recursing upwards, but stop if we have gone more than 2
levels up or we have reached /foo/bar.
The assumption here is that /foo/bar would actually be /Users/username
and searching the developer's entire home directory is likely to be too
expensive.
Similarly, if the project is in some subdirectory heirarchy, then if
we are three levels up then that search is likely to be large and too
expensive also.
*/
func kz_findFile(workspacePath : String, _ fileName : String) -> String? {
var thisWorkspaceCache = kz_filePathCache[workspacePath] ?? [:]
if let result = thisWorkspaceCache[fileName] {
if NSFileManager.defaultManager().fileExistsAtPath(result) {
return result
}
}
var searchPath = workspacePath
var prevSearchPath : String? = nil
var searchCount = 0
while true {
let result = kz_findFile(fileName, searchPath, prevSearchPath)
if result != nil && !result!.isEmpty {
thisWorkspaceCache[fileName] = result
kz_filePathCache[workspacePath] = thisWorkspaceCache
return result
}
prevSearchPath = searchPath
searchPath = (searchPath as NSString).stringByDeletingLastPathComponent
searchCount++
let searchPathCount = searchPath.componentsSeparatedByString("/").count
if searchPathCount <= 3 || searchCount >= 2 {
return nil
}
}
}
func kz_findFile(fileName : String, _ searchPath : String, _ prevSearchPath : String?) -> String? {
let args = (prevSearchPath == nil ?
["-L", searchPath, "-name", fileName, "-print", "-quit"] :
["-L", searchPath, "-name", prevSearchPath!, "-prune", "-o", "-name", fileName, "-print", "-quit"])
return KZPluginHelper.runShellCommand("/usr/bin/find", arguments: args)
}
| mit | d891707510d9e03db1d3f8506225e933 | 34.115385 | 121 | 0.629354 | 4.795168 | false | false | false | false |
rshuston/ClosestPointsWorkshop | ClosestPoints/ClosestPointsTests/CombinationSolverTests.swift | 1 | 11703 | //
// CombinationSolverTests.swift
// ClosestPoints
//
// Created by Robert Huston on 12/7/16.
// Copyright © 2016 Pinpoint Dynamics. All rights reserved.
//
import XCTest
@testable import ClosestPoints
class CombinationSolverTests: XCTestCase {
func test_findClosestPoints_ReturnsNilForEmptyPointSet() {
let points: [Point] = []
let subject = CombinationSolver()
let completionExpectation = expectation(description: "completion")
subject.findClosestPoints(points: points, monitor: nil, completion: {
(closestPoints: (Point, Point)?) -> Void in
XCTAssertNil(closestPoints)
completionExpectation.fulfill()
})
waitForExpectations(timeout: 1.0, handler: nil)
}
func test_findClosestPoints_ReturnsNilForInsufficientPointSet() {
var points: [Point] = []
let subject = CombinationSolver()
points.append(Point(x: 1, y: 2))
let completionExpectation = expectation(description: "completion")
subject.findClosestPoints(points: points, monitor: nil, completion: {
(closestPoints: (Point, Point)?) -> Void in
XCTAssertNil(closestPoints)
completionExpectation.fulfill()
})
waitForExpectations(timeout: 1.0, handler: nil)
}
func test_findClosestPoints_FindsClosestPointsForTrivialPointSet() {
var points: [Point] = []
let subject = CombinationSolver()
points.append(Point(x: 1, y: 2))
points.append(Point(x: 3, y: 4))
let completionExpectation = expectation(description: "completion")
subject.findClosestPoints(points: points, monitor: nil, completion: {
(closestPoints: (Point, Point)?) -> Void in
XCTAssertNotNil(closestPoints)
let listOrdered = (closestPoints?.0 == points[0])
if listOrdered {
XCTAssertEqual(closestPoints?.0, points[0])
XCTAssertEqual(closestPoints?.1, points[1])
} else {
XCTAssertEqual(closestPoints?.0, points[1])
XCTAssertEqual(closestPoints?.1, points[0])
}
completionExpectation.fulfill()
})
waitForExpectations(timeout: 1.0, handler: nil)
}
func test_findClosestPoints_CallsMonitorClosureForTrivialPointSet() {
var points: [Point] = []
let subject = CombinationSolver()
points.append(Point(x: 1, y: 2))
points.append(Point(x: 3, y: 4))
let completionExpectation = expectation(description: "completion")
var monitorCount = 0
subject.findClosestPoints(points: points, monitor: {
(checkRect: NSRect?, checkPoints: (Point, Point)?, closestPointsSoFar: (Point, Point)?) -> Bool in
monitorCount += 1
XCTAssertNotNil(checkRect)
XCTAssertFalse(NSIsEmptyRect(checkRect!))
XCTAssertNotNil(closestPointsSoFar)
XCTAssertEqual(checkPoints?.0, closestPointsSoFar?.0)
XCTAssertEqual(checkPoints?.1, closestPointsSoFar?.1)
let listOrdered = (closestPointsSoFar?.0 == points[0])
if listOrdered {
XCTAssertEqual(closestPointsSoFar?.0, points[0])
XCTAssertEqual(closestPointsSoFar?.1, points[1])
} else {
XCTAssertEqual(closestPointsSoFar?.0, points[1])
XCTAssertEqual(closestPointsSoFar?.1, points[0])
}
return true
}, completion: {
(closestPoints: (Point, Point)?) -> Void in
XCTAssertEqual(monitorCount, 1)
XCTAssertNotNil(closestPoints)
let listOrdered = (closestPoints?.0 == points[0])
if listOrdered {
XCTAssertEqual(closestPoints?.0, points[0])
XCTAssertEqual(closestPoints?.1, points[1])
} else {
XCTAssertEqual(closestPoints?.0, points[1])
XCTAssertEqual(closestPoints?.1, points[0])
}
completionExpectation.fulfill()
})
waitForExpectations(timeout: 1.0, handler: nil)
}
func test_findClosestPoints_FindsClosestPointsForTrinaryPointSet() {
var points: [Point] = []
let subject = CombinationSolver()
points.append(Point(x: 1, y: 2))
points.append(Point(x: 100, y: 100))
points.append(Point(x: 3, y: 4))
let completionExpectation = expectation(description: "completion")
subject.findClosestPoints(points: points, monitor: nil, completion: {
(closestPoints: (Point, Point)?) -> Void in
XCTAssertNotNil(closestPoints)
let listOrdered = (closestPoints?.0 == points[0])
if listOrdered {
XCTAssertEqual(closestPoints?.0, points[0])
XCTAssertEqual(closestPoints?.1, points[2])
} else {
XCTAssertEqual(closestPoints?.0, points[2])
XCTAssertEqual(closestPoints?.1, points[0])
}
completionExpectation.fulfill()
})
waitForExpectations(timeout: 1.0, handler: nil)
}
func test_findClosestPoints_CallsMonitorClosureForTrinaryPointSet() {
var points: [Point] = []
let subject = CombinationSolver()
points.append(Point(x: 1, y: 2))
points.append(Point(x: 100, y: 100))
points.append(Point(x: 3, y: 4))
let completionExpectation = expectation(description: "completion")
var monitorCount = 0
subject.findClosestPoints(points: points, monitor: {
(checkRect: NSRect?, checkPoints: (Point, Point)?, closestPointsSoFar: (Point, Point)?) -> Bool in
monitorCount += 1
XCTAssertNotNil(closestPointsSoFar)
return true
}, completion: {
(closestPoints: (Point, Point)?) -> Void in
XCTAssertEqual(monitorCount, 3) // Combination (nCr) of 3C2 = 3
XCTAssertNotNil(closestPoints)
let listOrdered = (closestPoints?.0 == points[0])
if listOrdered {
XCTAssertEqual(closestPoints?.0, points[0])
XCTAssertEqual(closestPoints?.1, points[2])
} else {
XCTAssertEqual(closestPoints?.0, points[2])
XCTAssertEqual(closestPoints?.1, points[0])
}
completionExpectation.fulfill()
})
waitForExpectations(timeout: 1.0, handler: nil)
}
func test_findClosestPoints_CanAbortFromMonitorClosureForTrinaryPointSet() {
var points: [Point] = []
let subject = CombinationSolver()
points.append(Point(x: 1, y: 2))
points.append(Point(x: 100, y: 100))
points.append(Point(x: 3, y: 4))
let completionExpectation = expectation(description: "completion")
var monitorCount = 0
subject.findClosestPoints(points: points, monitor: {
(checkRect: NSRect?, checkPoints: (Point, Point)?, closestPointsSoFar: (Point, Point)?) -> Bool in
monitorCount += 1
XCTAssertNotNil(closestPointsSoFar)
return false
}, completion: {
(closestPoints: (Point, Point)?) -> Void in
XCTAssertEqual(monitorCount, 1)
XCTAssertNotNil(closestPoints)
XCTAssertEqual(closestPoints?.0, points[0])
XCTAssertEqual(closestPoints?.1, points[1])
completionExpectation.fulfill()
})
waitForExpectations(timeout: 1.0, handler: nil)
}
func test_findClosestPoints_FindsClosestPointsForMultiplePointSet() {
var points: [Point] = []
let subject = CombinationSolver()
points.append(Point(x: 1, y: 2))
points.append(Point(x: 100, y: 100))
points.append(Point(x: 10, y: 10))
points.append(Point(x: 101, y: 101))
points.append(Point(x: 3, y: 4))
let completionExpectation = expectation(description: "completion")
subject.findClosestPoints(points: points, monitor: nil, completion: {
(closestPoints: (Point, Point)?) -> Void in
XCTAssertNotNil(closestPoints)
let listOrdered = (closestPoints?.0 == points[1])
if listOrdered {
XCTAssertEqual(closestPoints?.0, points[1])
XCTAssertEqual(closestPoints?.1, points[3])
} else {
XCTAssertEqual(closestPoints?.0, points[3])
XCTAssertEqual(closestPoints?.1, points[1])
}
completionExpectation.fulfill()
})
waitForExpectations(timeout: 1.0, handler: nil)
}
func test_findClosestPoints_CallsMonitorClosureForForMultiplePointSet() {
var points: [Point] = []
let subject = CombinationSolver()
points.append(Point(x: 1, y: 2))
points.append(Point(x: 100, y: 100))
points.append(Point(x: 10, y: 10))
points.append(Point(x: 101, y: 101))
points.append(Point(x: 3, y: 4))
let completionExpectation = expectation(description: "completion")
var monitorCount = 0
subject.findClosestPoints(points: points, monitor: {
(checkRect: NSRect?, checkPoints: (Point, Point)?, closestPointsSoFar: (Point, Point)?) -> Bool in
monitorCount += 1
XCTAssertNotNil(closestPointsSoFar)
return true
}, completion: {
(closestPoints: (Point, Point)?) -> Void in
XCTAssertEqual(monitorCount, 10) // Combination (nCr) of 5C2 = 10
XCTAssertNotNil(closestPoints)
let listOrdered = (closestPoints?.0 == points[1])
if listOrdered {
XCTAssertEqual(closestPoints?.0, points[1])
XCTAssertEqual(closestPoints?.1, points[3])
} else {
XCTAssertEqual(closestPoints?.0, points[3])
XCTAssertEqual(closestPoints?.1, points[1])
}
completionExpectation.fulfill()
})
waitForExpectations(timeout: 1.0, handler: nil)
}
func test_findClosestPoints_FindsClosestPointsForThirteenPointSet() {
var points: [Point] = []
let subject = CombinationSolver()
points.append(Point(x: 31, y: 17))
points.append(Point(x: 21, y: 23)) // first of closest pair
points.append(Point(x: 3, y: 15))
points.append(Point(x: 15, y: 31))
points.append(Point(x: 35, y: 25))
points.append(Point(x: 29, y: 11))
points.append(Point(x: 17, y: 21)) // second of closest pair
points.append(Point(x: 5, y: 27))
points.append(Point(x: 11, y: 9))
points.append(Point(x: 13, y: 37))
points.append(Point(x: 7, y: 19))
points.append(Point(x: 33, y: 5))
points.append(Point(x: 25, y: 29))
let completionExpectation = expectation(description: "completion")
subject.findClosestPoints(points: points, monitor: nil, completion: {
(closestPoints: (Point, Point)?) -> Void in
XCTAssertNotNil(closestPoints)
let listOrdered = (closestPoints?.0 == points[1])
if listOrdered {
XCTAssertEqual(closestPoints?.0, points[1])
XCTAssertEqual(closestPoints?.1, points[6])
} else {
XCTAssertEqual(closestPoints?.0, points[6])
XCTAssertEqual(closestPoints?.1, points[1])
}
completionExpectation.fulfill()
})
waitForExpectations(timeout: 1.0, handler: nil)
}
}
| mit | 847f85cbe07bc671beb643c95b4105ae | 33.017442 | 110 | 0.590754 | 4.528638 | false | false | false | false |
Shopify/mobile-buy-sdk-ios | Buy/Generated/Storefront/CartLine.swift | 1 | 12321 | //
// CartLine.swift
// Buy
//
// Created by Shopify.
// Copyright (c) 2017 Shopify Inc. All rights reserved.
//
// 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
extension Storefront {
/// Represents information about the merchandise in the cart.
open class CartLineQuery: GraphQL.AbstractQuery, GraphQLQuery {
public typealias Response = CartLine
/// An attribute associated with the cart line.
///
/// - parameters:
/// - key: The key of the attribute.
///
@discardableResult
open func attribute(alias: String? = nil, key: String, _ subfields: (AttributeQuery) -> Void) -> CartLineQuery {
var args: [String] = []
args.append("key:\(GraphQL.quoteString(input: key))")
let argsString = "(\(args.joined(separator: ",")))"
let subquery = AttributeQuery()
subfields(subquery)
addField(field: "attribute", aliasSuffix: alias, args: argsString, subfields: subquery)
return self
}
/// The attributes associated with the cart line. Attributes are represented as
/// key-value pairs.
@discardableResult
open func attributes(alias: String? = nil, _ subfields: (AttributeQuery) -> Void) -> CartLineQuery {
let subquery = AttributeQuery()
subfields(subquery)
addField(field: "attributes", aliasSuffix: alias, subfields: subquery)
return self
}
/// The cost of the merchandise that the buyer will pay for at checkout. The
/// costs are subject to change and changes will be reflected at checkout.
@discardableResult
open func cost(alias: String? = nil, _ subfields: (CartLineCostQuery) -> Void) -> CartLineQuery {
let subquery = CartLineCostQuery()
subfields(subquery)
addField(field: "cost", aliasSuffix: alias, subfields: subquery)
return self
}
/// The discounts that have been applied to the cart line.
@discardableResult
open func discountAllocations(alias: String? = nil, _ subfields: (CartDiscountAllocationQuery) -> Void) -> CartLineQuery {
let subquery = CartDiscountAllocationQuery()
subfields(subquery)
addField(field: "discountAllocations", aliasSuffix: alias, subfields: subquery)
return self
}
/// The estimated cost of the merchandise that the buyer will pay for at
/// checkout. The estimated costs are subject to change and changes will be
/// reflected at checkout.
@available(*, deprecated, message:"Use `cost` instead.")
@discardableResult
open func estimatedCost(alias: String? = nil, _ subfields: (CartLineEstimatedCostQuery) -> Void) -> CartLineQuery {
let subquery = CartLineEstimatedCostQuery()
subfields(subquery)
addField(field: "estimatedCost", aliasSuffix: alias, subfields: subquery)
return self
}
/// A globally-unique identifier.
@discardableResult
open func id(alias: String? = nil) -> CartLineQuery {
addField(field: "id", aliasSuffix: alias)
return self
}
/// The merchandise that the buyer intends to purchase.
@discardableResult
open func merchandise(alias: String? = nil, _ subfields: (MerchandiseQuery) -> Void) -> CartLineQuery {
let subquery = MerchandiseQuery()
subfields(subquery)
addField(field: "merchandise", aliasSuffix: alias, subfields: subquery)
return self
}
/// The quantity of the merchandise that the customer intends to purchase.
@discardableResult
open func quantity(alias: String? = nil) -> CartLineQuery {
addField(field: "quantity", aliasSuffix: alias)
return self
}
/// The selling plan associated with the cart line and the effect that each
/// selling plan has on variants when they're purchased.
@discardableResult
open func sellingPlanAllocation(alias: String? = nil, _ subfields: (SellingPlanAllocationQuery) -> Void) -> CartLineQuery {
let subquery = SellingPlanAllocationQuery()
subfields(subquery)
addField(field: "sellingPlanAllocation", aliasSuffix: alias, subfields: subquery)
return self
}
}
/// Represents information about the merchandise in the cart.
open class CartLine: GraphQL.AbstractResponse, GraphQLObject, Node {
public typealias Query = CartLineQuery
internal override func deserializeValue(fieldName: String, value: Any) throws -> Any? {
let fieldValue = value
switch fieldName {
case "attribute":
if value is NSNull { return nil }
guard let value = value as? [String: Any] else {
throw SchemaViolationError(type: CartLine.self, field: fieldName, value: fieldValue)
}
return try Attribute(fields: value)
case "attributes":
guard let value = value as? [[String: Any]] else {
throw SchemaViolationError(type: CartLine.self, field: fieldName, value: fieldValue)
}
return try value.map { return try Attribute(fields: $0) }
case "cost":
guard let value = value as? [String: Any] else {
throw SchemaViolationError(type: CartLine.self, field: fieldName, value: fieldValue)
}
return try CartLineCost(fields: value)
case "discountAllocations":
guard let value = value as? [[String: Any]] else {
throw SchemaViolationError(type: CartLine.self, field: fieldName, value: fieldValue)
}
return try value.map { return try UnknownCartDiscountAllocation.create(fields: $0) }
case "estimatedCost":
guard let value = value as? [String: Any] else {
throw SchemaViolationError(type: CartLine.self, field: fieldName, value: fieldValue)
}
return try CartLineEstimatedCost(fields: value)
case "id":
guard let value = value as? String else {
throw SchemaViolationError(type: CartLine.self, field: fieldName, value: fieldValue)
}
return GraphQL.ID(rawValue: value)
case "merchandise":
guard let value = value as? [String: Any] else {
throw SchemaViolationError(type: CartLine.self, field: fieldName, value: fieldValue)
}
return try UnknownMerchandise.create(fields: value)
case "quantity":
guard let value = value as? Int else {
throw SchemaViolationError(type: CartLine.self, field: fieldName, value: fieldValue)
}
return Int32(value)
case "sellingPlanAllocation":
if value is NSNull { return nil }
guard let value = value as? [String: Any] else {
throw SchemaViolationError(type: CartLine.self, field: fieldName, value: fieldValue)
}
return try SellingPlanAllocation(fields: value)
default:
throw SchemaViolationError(type: CartLine.self, field: fieldName, value: fieldValue)
}
}
/// An attribute associated with the cart line.
open var attribute: Storefront.Attribute? {
return internalGetAttribute()
}
open func aliasedAttribute(alias: String) -> Storefront.Attribute? {
return internalGetAttribute(alias: alias)
}
func internalGetAttribute(alias: String? = nil) -> Storefront.Attribute? {
return field(field: "attribute", aliasSuffix: alias) as! Storefront.Attribute?
}
/// The attributes associated with the cart line. Attributes are represented as
/// key-value pairs.
open var attributes: [Storefront.Attribute] {
return internalGetAttributes()
}
func internalGetAttributes(alias: String? = nil) -> [Storefront.Attribute] {
return field(field: "attributes", aliasSuffix: alias) as! [Storefront.Attribute]
}
/// The cost of the merchandise that the buyer will pay for at checkout. The
/// costs are subject to change and changes will be reflected at checkout.
open var cost: Storefront.CartLineCost {
return internalGetCost()
}
func internalGetCost(alias: String? = nil) -> Storefront.CartLineCost {
return field(field: "cost", aliasSuffix: alias) as! Storefront.CartLineCost
}
/// The discounts that have been applied to the cart line.
open var discountAllocations: [CartDiscountAllocation] {
return internalGetDiscountAllocations()
}
func internalGetDiscountAllocations(alias: String? = nil) -> [CartDiscountAllocation] {
return field(field: "discountAllocations", aliasSuffix: alias) as! [CartDiscountAllocation]
}
/// The estimated cost of the merchandise that the buyer will pay for at
/// checkout. The estimated costs are subject to change and changes will be
/// reflected at checkout.
@available(*, deprecated, message:"Use `cost` instead.")
open var estimatedCost: Storefront.CartLineEstimatedCost {
return internalGetEstimatedCost()
}
func internalGetEstimatedCost(alias: String? = nil) -> Storefront.CartLineEstimatedCost {
return field(field: "estimatedCost", aliasSuffix: alias) as! Storefront.CartLineEstimatedCost
}
/// A globally-unique identifier.
open var id: GraphQL.ID {
return internalGetId()
}
func internalGetId(alias: String? = nil) -> GraphQL.ID {
return field(field: "id", aliasSuffix: alias) as! GraphQL.ID
}
/// The merchandise that the buyer intends to purchase.
open var merchandise: Merchandise {
return internalGetMerchandise()
}
func internalGetMerchandise(alias: String? = nil) -> Merchandise {
return field(field: "merchandise", aliasSuffix: alias) as! Merchandise
}
/// The quantity of the merchandise that the customer intends to purchase.
open var quantity: Int32 {
return internalGetQuantity()
}
func internalGetQuantity(alias: String? = nil) -> Int32 {
return field(field: "quantity", aliasSuffix: alias) as! Int32
}
/// The selling plan associated with the cart line and the effect that each
/// selling plan has on variants when they're purchased.
open var sellingPlanAllocation: Storefront.SellingPlanAllocation? {
return internalGetSellingPlanAllocation()
}
func internalGetSellingPlanAllocation(alias: String? = nil) -> Storefront.SellingPlanAllocation? {
return field(field: "sellingPlanAllocation", aliasSuffix: alias) as! Storefront.SellingPlanAllocation?
}
internal override func childResponseObjectMap() -> [GraphQL.AbstractResponse] {
var response: [GraphQL.AbstractResponse] = []
objectMap.keys.forEach {
switch($0) {
case "attribute":
if let value = internalGetAttribute() {
response.append(value)
response.append(contentsOf: value.childResponseObjectMap())
}
case "attributes":
internalGetAttributes().forEach {
response.append($0)
response.append(contentsOf: $0.childResponseObjectMap())
}
case "cost":
response.append(internalGetCost())
response.append(contentsOf: internalGetCost().childResponseObjectMap())
case "discountAllocations":
internalGetDiscountAllocations().forEach {
response.append(($0 as! GraphQL.AbstractResponse))
response.append(contentsOf: ($0 as! GraphQL.AbstractResponse).childResponseObjectMap())
}
case "estimatedCost":
response.append(internalGetEstimatedCost())
response.append(contentsOf: internalGetEstimatedCost().childResponseObjectMap())
case "merchandise":
response.append((internalGetMerchandise() as! GraphQL.AbstractResponse))
response.append(contentsOf: (internalGetMerchandise() as! GraphQL.AbstractResponse).childResponseObjectMap())
case "sellingPlanAllocation":
if let value = internalGetSellingPlanAllocation() {
response.append(value)
response.append(contentsOf: value.childResponseObjectMap())
}
default:
break
}
}
return response
}
}
}
| mit | 9e29d51bb06e7f96619d48e404ad08e3 | 35.131965 | 125 | 0.718611 | 4.029104 | false | false | false | false |
victor-pavlychko/SwiftyTasks | SwiftyTasks/Tasks/AsyncBlockTask.swift | 1 | 2916 | //
// AsyncBlockTask.swift
// SwiftyTasks
//
// Created by Victor Pavlychko on 9/12/16.
// Copyright © 2016 address.wtf. All rights reserved.
//
import Foundation
/// `AsyncTask` subclass to wrap any asynchronous code block into an `AsyncTask`
public final class AsyncBlockTask<ResultType>: AsyncTask<ResultType> {
private var _block: ((AsyncBlockTask<ResultType>) throws -> Void)!
/// Initializes `AsyncBlockTask` with a code block tacking completion handler with result
///
/// - Parameters:
/// - block: code block
/// - completionBlock: completion handler passed to the code block
/// - result: task result returned from the code block
/// - Returns: Newly created `AsyncBlockTask` instance
public init(_ block: @escaping (_ completionBlock: @escaping (_ result: ResultType) -> Void) throws -> Void) {
_block = { try block($0.finish) }
}
/// Initializes `AsyncBlockTask` with a code block tacking completion handler with optional result and error
///
/// - Parameters:
/// - block: code block
/// - completionBlock: completion handler passed to the code block
/// - result: task result returned from the code block
/// - error: task error returned from the code block
/// - Returns: Newly created `AsyncBlockTask` instance
public init(_ block: @escaping (_ completionBlock: @escaping (_ result: ResultType?, _ error: Error?) -> Void) throws -> Void) {
_block = { try block($0.finish) }
}
/// Initializes `AsyncBlockTask` with a code block tacking completion handler with optional result
///
/// - Parameters:
/// - block: code block
/// - completionBlock: completion handler passed to the code block
/// - result: optional task result returned from the code block
/// - Returns: Newly created `AsyncBlockTask` instance
public init(_ block: @escaping (_ completionBlock: @escaping (_ result: ResultType?) -> Void) throws -> Void) {
_block = { try block($0.finish) }
}
/// Initializes `AsyncBlockTask` with a code block tacking completion handler with a result block
///
/// - Parameters:
/// - block: code block
/// - completionBlock: completion handler passed to the code block
/// - resultBlock: task result returned from the code block
/// - Returns: Newly created `AsyncBlockTask` instance
public init(_ block: @escaping (_ completionBlock: @escaping (_ resultBlock: () throws -> ResultType) -> Void) throws -> Void) {
_block = { try block($0.finish) }
}
/// Starts execution. Do not call this method yourself.
public override func main() {
do {
try _block(self)
_block = nil
} catch {
finish(error: error)
}
}
}
| mit | 4fec2fd60debd32005ae68cd19c49eed | 40.642857 | 132 | 0.617496 | 4.583333 | false | false | false | false |
mparrish91/gifRecipes | framework/vendor/MiniKeychain/MiniKeychain/MiniKeychain.swift | 1 | 66344 | //
// MiniKeychain.swift
// MiniKeychain
//
// Created by sonson on 2016/08/18.
// Copyright © 2016年 sonson. All rights reserved.
//
#if os(iOS) || os(tvOS)
import UIKit
#elseif os(macOS)
import Cocoa
#endif
import Security
class MiniKeychain {
let service: String?
let accessGroup: String?
public init() {
self.service = nil
self.accessGroup = nil
}
public init(service: String) {
self.service = service
self.accessGroup = nil
}
public init(accessGroup: String) {
if let bundleIdentifier = Bundle.main.bundleIdentifier {
self.service = bundleIdentifier
} else {
self.service = nil
}
self.accessGroup = accessGroup
}
public init(service: String, accessGroup: String) {
self.service = service
self.accessGroup = accessGroup
}
func getDefaultQuery() -> [String: Any] {
var query: [String: Any] = [kSecClass as String: kSecClassGenericPassword as String]
if let service = self.service {
query[kSecAttrService as String] = service
}
query[kSecAttrSynchronizable as String] = kSecAttrSynchronizableAny as String
// Access group is not supported on any simulators.
#if (!arch(i386) && !arch(x86_64)) || (!os(iOS) && !os(watchOS) && !os(tvOS))
if let accessGroup = self.accessGroup {
query[kSecAttrAccessGroup as String] = accessGroup
}
#endif
return query
}
public func save(key: String, data: Data) throws {
var query = getDefaultQuery()
query[kSecAttrAccount as String] = key
query[kSecValueData as String] = data
SecItemDelete(query as CFDictionary)
let status: OSStatus = SecItemAdd(query as CFDictionary, nil)
let message = Status(status: status).description
if status != noErr {
let error = NSError(domain: "a", code: Int(status), userInfo: [NSLocalizedDescriptionKey: message])
print("OSStatus error:[\(error.code)] \(error.localizedDescription)")
throw error
}
}
public func data(of key: String) throws -> Data {
var query = getDefaultQuery()
query[kSecAttrAccount as String] = key
query[kSecReturnData as String] = kCFBooleanTrue
query[kSecMatchLimit as String] = kSecMatchLimitOne
if let service = service {
query[kSecAttrService as String] = service
}
var result: AnyObject?
let status = withUnsafeMutablePointer(to: &result) { SecItemCopyMatching(query as CFDictionary, UnsafeMutablePointer($0)) }
if status == noErr {
if let data = result as? Data {
return data
} else {
let error = NSError(domain: "a", code: Int(1), userInfo: [NSLocalizedDescriptionKey: "a"])
throw error
}
} else {
let message = Status(status: status).description
let error = NSError(domain: "a", code: Int(status), userInfo: [NSLocalizedDescriptionKey: message])
print("OSStatus error:[\(error.code)] \(error.localizedDescription)")
throw error
}
}
public func keys() throws -> [String] {
var query = getDefaultQuery()
query[kSecReturnData as String] = kCFBooleanFalse
query[kSecReturnAttributes as String] = kCFBooleanTrue
query[kSecMatchLimit as String] = kSecMatchLimitAll
if let service = service {
query[kSecAttrService as String] = service
}
var result: AnyObject?
let status = withUnsafeMutablePointer(to: &result) { SecItemCopyMatching(query as CFDictionary, UnsafeMutablePointer($0)) }
let message = Status(status: status).description
let error = NSError(domain: "a", code: Int(status), userInfo: [NSLocalizedDescriptionKey: message])
print("OSStatus error:[\(error.code)] \(error.localizedDescription)")
switch status {
case noErr:
if let dictionaries = result as? [[String: Any]] {
return dictionaries.flatMap({$0["acct"] as? String})
} else {
let error = NSError(domain: "a", code: Int(Status.unexpectedError.rawValue), userInfo: [NSLocalizedDescriptionKey: ""])
throw error
}
case errSecItemNotFound:
return []
default:
throw error
}
}
@discardableResult
public func delete(key: String) -> Bool {
var query = getDefaultQuery()
query[kSecAttrAccount as String] = key
let status: OSStatus = SecItemDelete(query as CFDictionary)
return status == noErr
}
@discardableResult
public func clear() -> Bool {
let query = getDefaultQuery()
let status: OSStatus = SecItemDelete(query as CFDictionary)
return status == noErr
}
}
public enum Status: OSStatus, Error {
case success = 0
case unimplemented = -4
case diskFull = -34
case io = -36
case opWr = -49
case param = -50
case wrPerm = -61
case allocate = -108
case userCanceled = -128
case badReq = -909
case internalComponent = -2070
case notAvailable = -25291
case readOnly = -25292
case authFailed = -25293
case noSuchKeychain = -25294
case invalidKeychain = -25295
case duplicateKeychain = -25296
case duplicateCallback = -25297
case invalidCallback = -25298
case duplicateItem = -25299
case itemNotFound = -25300
case bufferTooSmall = -25301
case dataTooLarge = -25302
case noSuchAttr = -25303
case invalidItemRef = -25304
case invalidSearchRef = -25305
case noSuchClass = -25306
case noDefaultKeychain = -25307
case interactionNotAllowed = -25308
case readOnlyAttr = -25309
case wrongSecVersion = -25310
case keySizeNotAllowed = -25311
case noStorageModule = -25312
case noCertificateModule = -25313
case noPolicyModule = -25314
case interactionRequired = -25315
case dataNotAvailable = -25316
case dataNotModifiable = -25317
case createChainFailed = -25318
case invalidPrefsDomain = -25319
case inDarkWake = -25320
case aclNotSimple = -25240
case policyNotFound = -25241
case invalidTrustSetting = -25242
case noAccessForItem = -25243
case invalidOwnerEdit = -25244
case trustNotAvailable = -25245
case unsupportedFormat = -25256
case unknownFormat = -25257
case keyIsSensitive = -25258
case multiplePrivKeys = -25259
case passphraseRequired = -25260
case invalidPasswordRef = -25261
case invalidTrustSettings = -25262
case noTrustSettings = -25263
case pkcs12VerifyFailure = -25264
case invalidCertificate = -26265
case notSigner = -26267
case policyDenied = -26270
case invalidKey = -26274
case decode = -26275
case `internal` = -26276
case unsupportedAlgorithm = -26268
case unsupportedOperation = -26271
case unsupportedPadding = -26273
case itemInvalidKey = -34000
case itemInvalidKeyType = -34001
case itemInvalidValue = -34002
case itemClassMissing = -34003
case itemMatchUnsupported = -34004
case useItemListUnsupported = -34005
case useKeychainUnsupported = -34006
case useKeychainListUnsupported = -34007
case returnDataUnsupported = -34008
case returnAttributesUnsupported = -34009
case returnRefUnsupported = -34010
case returnPersitentRefUnsupported = -34011
case valueRefUnsupported = -34012
case valuePersistentRefUnsupported = -34013
case returnMissingPointer = -34014
case matchLimitUnsupported = -34015
case itemIllegalQuery = -34016
case waitForCallback = -34017
case missingEntitlement = -34018
case upgradePending = -34019
case mpSignatureInvalid = -25327
case otrTooOld = -25328
case otrIDTooNew = -25329
case serviceNotAvailable = -67585
case insufficientClientID = -67586
case deviceReset = -67587
case deviceFailed = -67588
case appleAddAppACLSubject = -67589
case applePublicKeyIncomplete = -67590
case appleSignatureMismatch = -67591
case appleInvalidKeyStartDate = -67592
case appleInvalidKeyEndDate = -67593
case conversionError = -67594
case appleSSLv2Rollback = -67595
case quotaExceeded = -67596
case fileTooBig = -67597
case invalidDatabaseBlob = -67598
case invalidKeyBlob = -67599
case incompatibleDatabaseBlob = -67600
case incompatibleKeyBlob = -67601
case hostNameMismatch = -67602
case unknownCriticalExtensionFlag = -67603
case noBasicConstraints = -67604
case noBasicConstraintsCA = -67605
case invalidAuthorityKeyID = -67606
case invalidSubjectKeyID = -67607
case invalidKeyUsageForPolicy = -67608
case invalidExtendedKeyUsage = -67609
case invalidIDLinkage = -67610
case pathLengthConstraintExceeded = -67611
case invalidRoot = -67612
case crlExpired = -67613
case crlNotValidYet = -67614
case crlNotFound = -67615
case crlServerDown = -67616
case crlBadURI = -67617
case unknownCertExtension = -67618
case unknownCRLExtension = -67619
case crlNotTrusted = -67620
case crlPolicyFailed = -67621
case idpFailure = -67622
case smimeEmailAddressesNotFound = -67623
case smimeBadExtendedKeyUsage = -67624
case smimeBadKeyUsage = -67625
case smimeKeyUsageNotCritical = -67626
case smimeNoEmailAddress = -67627
case smimeSubjAltNameNotCritical = -67628
case sslBadExtendedKeyUsage = -67629
case ocspBadResponse = -67630
case ocspBadRequest = -67631
case ocspUnavailable = -67632
case ocspStatusUnrecognized = -67633
case endOfData = -67634
case incompleteCertRevocationCheck = -67635
case networkFailure = -67636
case ocspNotTrustedToAnchor = -67637
case recordModified = -67638
case ocspSignatureError = -67639
case ocspNoSigner = -67640
case ocspResponderMalformedReq = -67641
case ocspResponderInternalError = -67642
case ocspResponderTryLater = -67643
case ocspResponderSignatureRequired = -67644
case ocspResponderUnauthorized = -67645
case ocspResponseNonceMismatch = -67646
case codeSigningBadCertChainLength = -67647
case codeSigningNoBasicConstraints = -67648
case codeSigningBadPathLengthConstraint = -67649
case codeSigningNoExtendedKeyUsage = -67650
case codeSigningDevelopment = -67651
case resourceSignBadCertChainLength = -67652
case resourceSignBadExtKeyUsage = -67653
case trustSettingDeny = -67654
case invalidSubjectName = -67655
case unknownQualifiedCertStatement = -67656
case mobileMeRequestQueued = -67657
case mobileMeRequestRedirected = -67658
case mobileMeServerError = -67659
case mobileMeServerNotAvailable = -67660
case mobileMeServerAlreadyExists = -67661
case mobileMeServerServiceErr = -67662
case mobileMeRequestAlreadyPending = -67663
case mobileMeNoRequestPending = -67664
case mobileMeCSRVerifyFailure = -67665
case mobileMeFailedConsistencyCheck = -67666
case notInitialized = -67667
case invalidHandleUsage = -67668
case pvcReferentNotFound = -67669
case functionIntegrityFail = -67670
case internalError = -67671
case memoryError = -67672
case invalidData = -67673
case mdsError = -67674
case invalidPointer = -67675
case selfCheckFailed = -67676
case functionFailed = -67677
case moduleManifestVerifyFailed = -67678
case invalidGUID = -67679
case invalidHandle = -67680
case invalidDBList = -67681
case invalidPassthroughID = -67682
case invalidNetworkAddress = -67683
case crlAlreadySigned = -67684
case invalidNumberOfFields = -67685
case verificationFailure = -67686
case unknownTag = -67687
case invalidSignature = -67688
case invalidName = -67689
case invalidCertificateRef = -67690
case invalidCertificateGroup = -67691
case tagNotFound = -67692
case invalidQuery = -67693
case invalidValue = -67694
case callbackFailed = -67695
case aclDeleteFailed = -67696
case aclReplaceFailed = -67697
case aclAddFailed = -67698
case aclChangeFailed = -67699
case invalidAccessCredentials = -67700
case invalidRecord = -67701
case invalidACL = -67702
case invalidSampleValue = -67703
case incompatibleVersion = -67704
case privilegeNotGranted = -67705
case invalidScope = -67706
case pvcAlreadyConfigured = -67707
case invalidPVC = -67708
case emmLoadFailed = -67709
case emmUnloadFailed = -67710
case addinLoadFailed = -67711
case invalidKeyRef = -67712
case invalidKeyHierarchy = -67713
case addinUnloadFailed = -67714
case libraryReferenceNotFound = -67715
case invalidAddinFunctionTable = -67716
case invalidServiceMask = -67717
case moduleNotLoaded = -67718
case invalidSubServiceID = -67719
case attributeNotInContext = -67720
case moduleManagerInitializeFailed = -67721
case moduleManagerNotFound = -67722
case eventNotificationCallbackNotFound = -67723
case inputLengthError = -67724
case outputLengthError = -67725
case privilegeNotSupported = -67726
case deviceError = -67727
case attachHandleBusy = -67728
case notLoggedIn = -67729
case algorithmMismatch = -67730
case keyUsageIncorrect = -67731
case keyBlobTypeIncorrect = -67732
case keyHeaderInconsistent = -67733
case unsupportedKeyFormat = -67734
case unsupportedKeySize = -67735
case invalidKeyUsageMask = -67736
case unsupportedKeyUsageMask = -67737
case invalidKeyAttributeMask = -67738
case unsupportedKeyAttributeMask = -67739
case invalidKeyLabel = -67740
case unsupportedKeyLabel = -67741
case invalidKeyFormat = -67742
case unsupportedVectorOfBuffers = -67743
case invalidInputVector = -67744
case invalidOutputVector = -67745
case invalidContext = -67746
case invalidAlgorithm = -67747
case invalidAttributeKey = -67748
case missingAttributeKey = -67749
case invalidAttributeInitVector = -67750
case missingAttributeInitVector = -67751
case invalidAttributeSalt = -67752
case missingAttributeSalt = -67753
case invalidAttributePadding = -67754
case missingAttributePadding = -67755
case invalidAttributeRandom = -67756
case missingAttributeRandom = -67757
case invalidAttributeSeed = -67758
case missingAttributeSeed = -67759
case invalidAttributePassphrase = -67760
case missingAttributePassphrase = -67761
case invalidAttributeKeyLength = -67762
case missingAttributeKeyLength = -67763
case invalidAttributeBlockSize = -67764
case missingAttributeBlockSize = -67765
case invalidAttributeOutputSize = -67766
case missingAttributeOutputSize = -67767
case invalidAttributeRounds = -67768
case missingAttributeRounds = -67769
case invalidAlgorithmParms = -67770
case missingAlgorithmParms = -67771
case invalidAttributeLabel = -67772
case missingAttributeLabel = -67773
case invalidAttributeKeyType = -67774
case missingAttributeKeyType = -67775
case invalidAttributeMode = -67776
case missingAttributeMode = -67777
case invalidAttributeEffectiveBits = -67778
case missingAttributeEffectiveBits = -67779
case invalidAttributeStartDate = -67780
case missingAttributeStartDate = -67781
case invalidAttributeEndDate = -67782
case missingAttributeEndDate = -67783
case invalidAttributeVersion = -67784
case missingAttributeVersion = -67785
case invalidAttributePrime = -67786
case missingAttributePrime = -67787
case invalidAttributeBase = -67788
case missingAttributeBase = -67789
case invalidAttributeSubprime = -67790
case missingAttributeSubprime = -67791
case invalidAttributeIterationCount = -67792
case missingAttributeIterationCount = -67793
case invalidAttributeDLDBHandle = -67794
case missingAttributeDLDBHandle = -67795
case invalidAttributeAccessCredentials = -67796
case missingAttributeAccessCredentials = -67797
case invalidAttributePublicKeyFormat = -67798
case missingAttributePublicKeyFormat = -67799
case invalidAttributePrivateKeyFormat = -67800
case missingAttributePrivateKeyFormat = -67801
case invalidAttributeSymmetricKeyFormat = -67802
case missingAttributeSymmetricKeyFormat = -67803
case invalidAttributeWrappedKeyFormat = -67804
case missingAttributeWrappedKeyFormat = -67805
case stagedOperationInProgress = -67806
case stagedOperationNotStarted = -67807
case verifyFailed = -67808
case querySizeUnknown = -67809
case blockSizeMismatch = -67810
case publicKeyInconsistent = -67811
case deviceVerifyFailed = -67812
case invalidLoginName = -67813
case alreadyLoggedIn = -67814
case invalidDigestAlgorithm = -67815
case invalidCRLGroup = -67816
case certificateCannotOperate = -67817
case certificateExpired = -67818
case certificateNotValidYet = -67819
case certificateRevoked = -67820
case certificateSuspended = -67821
case insufficientCredentials = -67822
case invalidAction = -67823
case invalidAuthority = -67824
case verifyActionFailed = -67825
case invalidCertAuthority = -67826
case invaldCRLAuthority = -67827
case invalidCRLEncoding = -67828
case invalidCRLType = -67829
case invalidCRL = -67830
case invalidFormType = -67831
case invalidID = -67832
case invalidIdentifier = -67833
case invalidIndex = -67834
case invalidPolicyIdentifiers = -67835
case invalidTimeString = -67836
case invalidReason = -67837
case invalidRequestInputs = -67838
case invalidResponseVector = -67839
case invalidStopOnPolicy = -67840
case invalidTuple = -67841
case multipleValuesUnsupported = -67842
case notTrusted = -67843
case noDefaultAuthority = -67844
case rejectedForm = -67845
case requestLost = -67846
case requestRejected = -67847
case unsupportedAddressType = -67848
case unsupportedService = -67849
case invalidTupleGroup = -67850
case invalidBaseACLs = -67851
case invalidTupleCredendtials = -67852
case invalidEncoding = -67853
case invalidValidityPeriod = -67854
case invalidRequestor = -67855
case requestDescriptor = -67856
case invalidBundleInfo = -67857
case invalidCRLIndex = -67858
case noFieldValues = -67859
case unsupportedFieldFormat = -67860
case unsupportedIndexInfo = -67861
case unsupportedLocality = -67862
case unsupportedNumAttributes = -67863
case unsupportedNumIndexes = -67864
case unsupportedNumRecordTypes = -67865
case fieldSpecifiedMultiple = -67866
case incompatibleFieldFormat = -67867
case invalidParsingModule = -67868
case databaseLocked = -67869
case datastoreIsOpen = -67870
case missingValue = -67871
case unsupportedQueryLimits = -67872
case unsupportedNumSelectionPreds = -67873
case unsupportedOperator = -67874
case invalidDBLocation = -67875
case invalidAccessRequest = -67876
case invalidIndexInfo = -67877
case invalidNewOwner = -67878
case invalidModifyMode = -67879
case missingRequiredExtension = -67880
case extendedKeyUsageNotCritical = -67881
case timestampMissing = -67882
case timestampInvalid = -67883
case timestampNotTrusted = -67884
case timestampServiceNotAvailable = -67885
case timestampBadAlg = -67886
case timestampBadRequest = -67887
case timestampBadDataFormat = -67888
case timestampTimeNotAvailable = -67889
case timestampUnacceptedPolicy = -67890
case timestampUnacceptedExtension = -67891
case timestampAddInfoNotAvailable = -67892
case timestampSystemFailure = -67893
case signingTimeMissing = -67894
case timestampRejection = -67895
case timestampWaiting = -67896
case timestampRevocationWarning = -67897
case timestampRevocationNotification = -67898
case unexpectedError = -99999
}
extension Status: RawRepresentable, CustomStringConvertible {
public init(status: OSStatus) {
if let mappedStatus = Status(rawValue: status) {
self = mappedStatus
} else {
self = .unexpectedError
}
}
public var description: String {
switch self {
case .success:
return "No error."
case .unimplemented:
return "Function or operation not implemented."
case .diskFull:
return "The disk is full."
case .io:
return "I/O error (bummers)"
case .opWr:
return "file already open with with write permission"
case .param:
return "One or more parameters passed to a function were not valid."
case .wrPerm:
return "write permissions error"
case .allocate:
return "Failed to allocate memory."
case .userCanceled:
return "User canceled the operation."
case .badReq:
return "Bad parameter or invalid state for operation."
case .internalComponent:
return ""
case .notAvailable:
return "No keychain is available. You may need to restart your computer."
case .readOnly:
return "This keychain cannot be modified."
case .authFailed:
return "The user name or passphrase you entered is not correct."
case .noSuchKeychain:
return "The specified keychain could not be found."
case .invalidKeychain:
return "The specified keychain is not a valid keychain file."
case .duplicateKeychain:
return "A keychain with the same name already exists."
case .duplicateCallback:
return "The specified callback function is already installed."
case .invalidCallback:
return "The specified callback function is not valid."
case .duplicateItem:
return "The specified item already exists in the keychain."
case .itemNotFound:
return "The specified item could not be found in the keychain."
case .bufferTooSmall:
return "There is not enough memory available to use the specified item."
case .dataTooLarge:
return "This item contains information which is too large or in a format that cannot be displayed."
case .noSuchAttr:
return "The specified attribute does not exist."
case .invalidItemRef:
return "The specified item is no longer valid. It may have been deleted from the keychain."
case .invalidSearchRef:
return "Unable to search the current keychain."
case .noSuchClass:
return "The specified item does not appear to be a valid keychain item."
case .noDefaultKeychain:
return "A default keychain could not be found."
case .interactionNotAllowed:
return "User interaction is not allowed."
case .readOnlyAttr:
return "The specified attribute could not be modified."
case .wrongSecVersion:
return "This keychain was created by a different version of the system software and cannot be opened."
case .keySizeNotAllowed:
return "This item specifies a key size which is too large."
case .noStorageModule:
return "A required component (data storage module) could not be loaded. You may need to restart your computer."
case .noCertificateModule:
return "A required component (certificate module) could not be loaded. You may need to restart your computer."
case .noPolicyModule:
return "A required component (policy module) could not be loaded. You may need to restart your computer."
case .interactionRequired:
return "User interaction is required, but is currently not allowed."
case .dataNotAvailable:
return "The contents of this item cannot be retrieved."
case .dataNotModifiable:
return "The contents of this item cannot be modified."
case .createChainFailed:
return "One or more certificates required to validate this certificate cannot be found."
case .invalidPrefsDomain:
return "The specified preferences domain is not valid."
case .inDarkWake:
return "In dark wake, no UI possible"
case .aclNotSimple:
return "The specified access control list is not in standard (simple) form."
case .policyNotFound:
return "The specified policy cannot be found."
case .invalidTrustSetting:
return "The specified trust setting is invalid."
case .noAccessForItem:
return "The specified item has no access control."
case .invalidOwnerEdit:
return "Invalid attempt to change the owner of this item."
case .trustNotAvailable:
return "No trust results are available."
case .unsupportedFormat:
return "Import/Export format unsupported."
case .unknownFormat:
return "Unknown format in import."
case .keyIsSensitive:
return "Key material must be wrapped for export."
case .multiplePrivKeys:
return "An attempt was made to import multiple private keys."
case .passphraseRequired:
return "Passphrase is required for import/export."
case .invalidPasswordRef:
return "The password reference was invalid."
case .invalidTrustSettings:
return "The Trust Settings Record was corrupted."
case .noTrustSettings:
return "No Trust Settings were found."
case .pkcs12VerifyFailure:
return "MAC verification failed during PKCS12 import (wrong password?)"
case .invalidCertificate:
return "This certificate could not be decoded."
case .notSigner:
return "A certificate was not signed by its proposed parent."
case .policyDenied:
return "The certificate chain was not trusted due to a policy not accepting it."
case .invalidKey:
return "The provided key material was not valid."
case .decode:
return "Unable to decode the provided data."
case .`internal`:
return "An internal error occurred in the Security framework."
case .unsupportedAlgorithm:
return "An unsupported algorithm was encountered."
case .unsupportedOperation:
return "The operation you requested is not supported by this key."
case .unsupportedPadding:
return "The padding you requested is not supported."
case .itemInvalidKey:
return "A string key in dictionary is not one of the supported keys."
case .itemInvalidKeyType:
return "A key in a dictionary is neither a CFStringRef nor a CFNumberRef."
case .itemInvalidValue:
return "A value in a dictionary is an invalid (or unsupported) CF type."
case .itemClassMissing:
return "No kSecItemClass key was specified in a dictionary."
case .itemMatchUnsupported:
return "The caller passed one or more kSecMatch keys to a function which does not support matches."
case .useItemListUnsupported:
return "The caller passed in a kSecUseItemList key to a function which does not support it."
case .useKeychainUnsupported:
return "The caller passed in a kSecUseKeychain key to a function which does not support it."
case .useKeychainListUnsupported:
return "The caller passed in a kSecUseKeychainList key to a function which does not support it."
case .returnDataUnsupported:
return "The caller passed in a kSecReturnData key to a function which does not support it."
case .returnAttributesUnsupported:
return "The caller passed in a kSecReturnAttributes key to a function which does not support it."
case .returnRefUnsupported:
return "The caller passed in a kSecReturnRef key to a function which does not support it."
case .returnPersitentRefUnsupported:
return "The caller passed in a kSecReturnPersistentRef key to a function which does not support it."
case .valueRefUnsupported:
return "The caller passed in a kSecValueRef key to a function which does not support it."
case .valuePersistentRefUnsupported:
return "The caller passed in a kSecValuePersistentRef key to a function which does not support it."
case .returnMissingPointer:
return "The caller passed asked for something to be returned but did not pass in a result pointer."
case .matchLimitUnsupported:
return "The caller passed in a kSecMatchLimit key to a call which does not support limits."
case .itemIllegalQuery:
return "The caller passed in a query which contained too many keys."
case .waitForCallback:
return "This operation is incomplete, until the callback is invoked (not an error)."
case .missingEntitlement:
return "Internal error when a required entitlement isn't present, client has neither application-identifier nor keychain-access-groups entitlements."
case .upgradePending:
return "Error returned if keychain database needs a schema migration but the device is locked, clients should wait for a device unlock notification and retry the command."
case .mpSignatureInvalid:
return "Signature invalid on MP message"
case .otrTooOld:
return "Message is too old to use"
case .otrIDTooNew:
return "Key ID is too new to use! Message from the future?"
case .serviceNotAvailable:
return "The required service is not available."
case .insufficientClientID:
return "The client ID is not correct."
case .deviceReset:
return "A device reset has occurred."
case .deviceFailed:
return "A device failure has occurred."
case .appleAddAppACLSubject:
return "Adding an application ACL subject failed."
case .applePublicKeyIncomplete:
return "The public key is incomplete."
case .appleSignatureMismatch:
return "A signature mismatch has occurred."
case .appleInvalidKeyStartDate:
return "The specified key has an invalid start date."
case .appleInvalidKeyEndDate:
return "The specified key has an invalid end date."
case .conversionError:
return "A conversion error has occurred."
case .appleSSLv2Rollback:
return "A SSLv2 rollback error has occurred."
case .quotaExceeded:
return "The quota was exceeded."
case .fileTooBig:
return "The file is too big."
case .invalidDatabaseBlob:
return "The specified database has an invalid blob."
case .invalidKeyBlob:
return "The specified database has an invalid key blob."
case .incompatibleDatabaseBlob:
return "The specified database has an incompatible blob."
case .incompatibleKeyBlob:
return "The specified database has an incompatible key blob."
case .hostNameMismatch:
return "A host name mismatch has occurred."
case .unknownCriticalExtensionFlag:
return "There is an unknown critical extension flag."
case .noBasicConstraints:
return "No basic constraints were found."
case .noBasicConstraintsCA:
return "No basic CA constraints were found."
case .invalidAuthorityKeyID:
return "The authority key ID is not valid."
case .invalidSubjectKeyID:
return "The subject key ID is not valid."
case .invalidKeyUsageForPolicy:
return "The key usage is not valid for the specified policy."
case .invalidExtendedKeyUsage:
return "The extended key usage is not valid."
case .invalidIDLinkage:
return "The ID linkage is not valid."
case .pathLengthConstraintExceeded:
return "The path length constraint was exceeded."
case .invalidRoot:
return "The root or anchor certificate is not valid."
case .crlExpired:
return "The CRL has expired."
case .crlNotValidYet:
return "The CRL is not yet valid."
case .crlNotFound:
return "The CRL was not found."
case .crlServerDown:
return "The CRL server is down."
case .crlBadURI:
return "The CRL has a bad Uniform Resource Identifier."
case .unknownCertExtension:
return "An unknown certificate extension was encountered."
case .unknownCRLExtension:
return "An unknown CRL extension was encountered."
case .crlNotTrusted:
return "The CRL is not trusted."
case .crlPolicyFailed:
return "The CRL policy failed."
case .idpFailure:
return "The issuing distribution point was not valid."
case .smimeEmailAddressesNotFound:
return "An email address mismatch was encountered."
case .smimeBadExtendedKeyUsage:
return "The appropriate extended key usage for SMIME was not found."
case .smimeBadKeyUsage:
return "The key usage is not compatible with SMIME."
case .smimeKeyUsageNotCritical:
return "The key usage extension is not marked as critical."
case .smimeNoEmailAddress:
return "No email address was found in the certificate."
case .smimeSubjAltNameNotCritical:
return "The subject alternative name extension is not marked as critical."
case .sslBadExtendedKeyUsage:
return "The appropriate extended key usage for SSL was not found."
case .ocspBadResponse:
return "The OCSP response was incorrect or could not be parsed."
case .ocspBadRequest:
return "The OCSP request was incorrect or could not be parsed."
case .ocspUnavailable:
return "OCSP service is unavailable."
case .ocspStatusUnrecognized:
return "The OCSP server did not recognize this certificate."
case .endOfData:
return "An end-of-data was detected."
case .incompleteCertRevocationCheck:
return "An incomplete certificate revocation check occurred."
case .networkFailure:
return "A network failure occurred."
case .ocspNotTrustedToAnchor:
return "The OCSP response was not trusted to a root or anchor certificate."
case .recordModified:
return "The record was modified."
case .ocspSignatureError:
return "The OCSP response had an invalid signature."
case .ocspNoSigner:
return "The OCSP response had no signer."
case .ocspResponderMalformedReq:
return "The OCSP responder was given a malformed request."
case .ocspResponderInternalError:
return "The OCSP responder encountered an internal error."
case .ocspResponderTryLater:
return "The OCSP responder is busy, try again later."
case .ocspResponderSignatureRequired:
return "The OCSP responder requires a signature."
case .ocspResponderUnauthorized:
return "The OCSP responder rejected this request as unauthorized."
case .ocspResponseNonceMismatch:
return "The OCSP response nonce did not match the request."
case .codeSigningBadCertChainLength:
return "Code signing encountered an incorrect certificate chain length."
case .codeSigningNoBasicConstraints:
return "Code signing found no basic constraints."
case .codeSigningBadPathLengthConstraint:
return "Code signing encountered an incorrect path length constraint."
case .codeSigningNoExtendedKeyUsage:
return "Code signing found no extended key usage."
case .codeSigningDevelopment:
return "Code signing indicated use of a development-only certificate."
case .resourceSignBadCertChainLength:
return "Resource signing has encountered an incorrect certificate chain length."
case .resourceSignBadExtKeyUsage:
return "Resource signing has encountered an error in the extended key usage."
case .trustSettingDeny:
return "The trust setting for this policy was set to Deny."
case .invalidSubjectName:
return "An invalid certificate subject name was encountered."
case .unknownQualifiedCertStatement:
return "An unknown qualified certificate statement was encountered."
case .mobileMeRequestQueued:
return "The MobileMe request will be sent during the next connection."
case .mobileMeRequestRedirected:
return "The MobileMe request was redirected."
case .mobileMeServerError:
return "A MobileMe server error occurred."
case .mobileMeServerNotAvailable:
return "The MobileMe server is not available."
case .mobileMeServerAlreadyExists:
return "The MobileMe server reported that the item already exists."
case .mobileMeServerServiceErr:
return "A MobileMe service error has occurred."
case .mobileMeRequestAlreadyPending:
return "A MobileMe request is already pending."
case .mobileMeNoRequestPending:
return "MobileMe has no request pending."
case .mobileMeCSRVerifyFailure:
return "A MobileMe CSR verification failure has occurred."
case .mobileMeFailedConsistencyCheck:
return "MobileMe has found a failed consistency check."
case .notInitialized:
return "A function was called without initializing CSSM."
case .invalidHandleUsage:
return "The CSSM handle does not match with the service type."
case .pvcReferentNotFound:
return "A reference to the calling module was not found in the list of authorized callers."
case .functionIntegrityFail:
return "A function address was not within the verified module."
case .internalError:
return "An internal error has occurred."
case .memoryError:
return "A memory error has occurred."
case .invalidData:
return "Invalid data was encountered."
case .mdsError:
return "A Module Directory Service error has occurred."
case .invalidPointer:
return "An invalid pointer was encountered."
case .selfCheckFailed:
return "Self-check has failed."
case .functionFailed:
return "A function has failed."
case .moduleManifestVerifyFailed:
return "A module manifest verification failure has occurred."
case .invalidGUID:
return "An invalid GUID was encountered."
case .invalidHandle:
return "An invalid handle was encountered."
case .invalidDBList:
return "An invalid DB list was encountered."
case .invalidPassthroughID:
return "An invalid passthrough ID was encountered."
case .invalidNetworkAddress:
return "An invalid network address was encountered."
case .crlAlreadySigned:
return "The certificate revocation list is already signed."
case .invalidNumberOfFields:
return "An invalid number of fields were encountered."
case .verificationFailure:
return "A verification failure occurred."
case .unknownTag:
return "An unknown tag was encountered."
case .invalidSignature:
return "An invalid signature was encountered."
case .invalidName:
return "An invalid name was encountered."
case .invalidCertificateRef:
return "An invalid certificate reference was encountered."
case .invalidCertificateGroup:
return "An invalid certificate group was encountered."
case .tagNotFound:
return "The specified tag was not found."
case .invalidQuery:
return "The specified query was not valid."
case .invalidValue:
return "An invalid value was detected."
case .callbackFailed:
return "A callback has failed."
case .aclDeleteFailed:
return "An ACL delete operation has failed."
case .aclReplaceFailed:
return "An ACL replace operation has failed."
case .aclAddFailed:
return "An ACL add operation has failed."
case .aclChangeFailed:
return "An ACL change operation has failed."
case .invalidAccessCredentials:
return "Invalid access credentials were encountered."
case .invalidRecord:
return "An invalid record was encountered."
case .invalidACL:
return "An invalid ACL was encountered."
case .invalidSampleValue:
return "An invalid sample value was encountered."
case .incompatibleVersion:
return "An incompatible version was encountered."
case .privilegeNotGranted:
return "The privilege was not granted."
case .invalidScope:
return "An invalid scope was encountered."
case .pvcAlreadyConfigured:
return "The PVC is already configured."
case .invalidPVC:
return "An invalid PVC was encountered."
case .emmLoadFailed:
return "The EMM load has failed."
case .emmUnloadFailed:
return "The EMM unload has failed."
case .addinLoadFailed:
return "The add-in load operation has failed."
case .invalidKeyRef:
return "An invalid key was encountered."
case .invalidKeyHierarchy:
return "An invalid key hierarchy was encountered."
case .addinUnloadFailed:
return "The add-in unload operation has failed."
case .libraryReferenceNotFound:
return "A library reference was not found."
case .invalidAddinFunctionTable:
return "An invalid add-in function table was encountered."
case .invalidServiceMask:
return "An invalid service mask was encountered."
case .moduleNotLoaded:
return "A module was not loaded."
case .invalidSubServiceID:
return "An invalid subservice ID was encountered."
case .attributeNotInContext:
return "An attribute was not in the context."
case .moduleManagerInitializeFailed:
return "A module failed to initialize."
case .moduleManagerNotFound:
return "A module was not found."
case .eventNotificationCallbackNotFound:
return "An event notification callback was not found."
case .inputLengthError:
return "An input length error was encountered."
case .outputLengthError:
return "An output length error was encountered."
case .privilegeNotSupported:
return "The privilege is not supported."
case .deviceError:
return "A device error was encountered."
case .attachHandleBusy:
return "The CSP handle was busy."
case .notLoggedIn:
return "You are not logged in."
case .algorithmMismatch:
return "An algorithm mismatch was encountered."
case .keyUsageIncorrect:
return "The key usage is incorrect."
case .keyBlobTypeIncorrect:
return "The key blob type is incorrect."
case .keyHeaderInconsistent:
return "The key header is inconsistent."
case .unsupportedKeyFormat:
return "The key header format is not supported."
case .unsupportedKeySize:
return "The key size is not supported."
case .invalidKeyUsageMask:
return "The key usage mask is not valid."
case .unsupportedKeyUsageMask:
return "The key usage mask is not supported."
case .invalidKeyAttributeMask:
return "The key attribute mask is not valid."
case .unsupportedKeyAttributeMask:
return "The key attribute mask is not supported."
case .invalidKeyLabel:
return "The key label is not valid."
case .unsupportedKeyLabel:
return "The key label is not supported."
case .invalidKeyFormat:
return "The key format is not valid."
case .unsupportedVectorOfBuffers:
return "The vector of buffers is not supported."
case .invalidInputVector:
return "The input vector is not valid."
case .invalidOutputVector:
return "The output vector is not valid."
case .invalidContext:
return "An invalid context was encountered."
case .invalidAlgorithm:
return "An invalid algorithm was encountered."
case .invalidAttributeKey:
return "A key attribute was not valid."
case .missingAttributeKey:
return "A key attribute was missing."
case .invalidAttributeInitVector:
return "An init vector attribute was not valid."
case .missingAttributeInitVector:
return "An init vector attribute was missing."
case .invalidAttributeSalt:
return "A salt attribute was not valid."
case .missingAttributeSalt:
return "A salt attribute was missing."
case .invalidAttributePadding:
return "A padding attribute was not valid."
case .missingAttributePadding:
return "A padding attribute was missing."
case .invalidAttributeRandom:
return "A random number attribute was not valid."
case .missingAttributeRandom:
return "A random number attribute was missing."
case .invalidAttributeSeed:
return "A seed attribute was not valid."
case .missingAttributeSeed:
return "A seed attribute was missing."
case .invalidAttributePassphrase:
return "A passphrase attribute was not valid."
case .missingAttributePassphrase:
return "A passphrase attribute was missing."
case .invalidAttributeKeyLength:
return "A key length attribute was not valid."
case .missingAttributeKeyLength:
return "A key length attribute was missing."
case .invalidAttributeBlockSize:
return "A block size attribute was not valid."
case .missingAttributeBlockSize:
return "A block size attribute was missing."
case .invalidAttributeOutputSize:
return "An output size attribute was not valid."
case .missingAttributeOutputSize:
return "An output size attribute was missing."
case .invalidAttributeRounds:
return "The number of rounds attribute was not valid."
case .missingAttributeRounds:
return "The number of rounds attribute was missing."
case .invalidAlgorithmParms:
return "An algorithm parameters attribute was not valid."
case .missingAlgorithmParms:
return "An algorithm parameters attribute was missing."
case .invalidAttributeLabel:
return "A label attribute was not valid."
case .missingAttributeLabel:
return "A label attribute was missing."
case .invalidAttributeKeyType:
return "A key type attribute was not valid."
case .missingAttributeKeyType:
return "A key type attribute was missing."
case .invalidAttributeMode:
return "A mode attribute was not valid."
case .missingAttributeMode:
return "A mode attribute was missing."
case .invalidAttributeEffectiveBits:
return "An effective bits attribute was not valid."
case .missingAttributeEffectiveBits:
return "An effective bits attribute was missing."
case .invalidAttributeStartDate:
return "A start date attribute was not valid."
case .missingAttributeStartDate:
return "A start date attribute was missing."
case .invalidAttributeEndDate:
return "An end date attribute was not valid."
case .missingAttributeEndDate:
return "An end date attribute was missing."
case .invalidAttributeVersion:
return "A version attribute was not valid."
case .missingAttributeVersion:
return "A version attribute was missing."
case .invalidAttributePrime:
return "A prime attribute was not valid."
case .missingAttributePrime:
return "A prime attribute was missing."
case .invalidAttributeBase:
return "A base attribute was not valid."
case .missingAttributeBase:
return "A base attribute was missing."
case .invalidAttributeSubprime:
return "A subprime attribute was not valid."
case .missingAttributeSubprime:
return "A subprime attribute was missing."
case .invalidAttributeIterationCount:
return "An iteration count attribute was not valid."
case .missingAttributeIterationCount:
return "An iteration count attribute was missing."
case .invalidAttributeDLDBHandle:
return "A database handle attribute was not valid."
case .missingAttributeDLDBHandle:
return "A database handle attribute was missing."
case .invalidAttributeAccessCredentials:
return "An access credentials attribute was not valid."
case .missingAttributeAccessCredentials:
return "An access credentials attribute was missing."
case .invalidAttributePublicKeyFormat:
return "A public key format attribute was not valid."
case .missingAttributePublicKeyFormat:
return "A public key format attribute was missing."
case .invalidAttributePrivateKeyFormat:
return "A private key format attribute was not valid."
case .missingAttributePrivateKeyFormat:
return "A private key format attribute was missing."
case .invalidAttributeSymmetricKeyFormat:
return "A symmetric key format attribute was not valid."
case .missingAttributeSymmetricKeyFormat:
return "A symmetric key format attribute was missing."
case .invalidAttributeWrappedKeyFormat:
return "A wrapped key format attribute was not valid."
case .missingAttributeWrappedKeyFormat:
return "A wrapped key format attribute was missing."
case .stagedOperationInProgress:
return "A staged operation is in progress."
case .stagedOperationNotStarted:
return "A staged operation was not started."
case .verifyFailed:
return "A cryptographic verification failure has occurred."
case .querySizeUnknown:
return "The query size is unknown."
case .blockSizeMismatch:
return "A block size mismatch occurred."
case .publicKeyInconsistent:
return "The public key was inconsistent."
case .deviceVerifyFailed:
return "A device verification failure has occurred."
case .invalidLoginName:
return "An invalid login name was detected."
case .alreadyLoggedIn:
return "The user is already logged in."
case .invalidDigestAlgorithm:
return "An invalid digest algorithm was detected."
case .invalidCRLGroup:
return "An invalid CRL group was detected."
case .certificateCannotOperate:
return "The certificate cannot operate."
case .certificateExpired:
return "An expired certificate was detected."
case .certificateNotValidYet:
return "The certificate is not yet valid."
case .certificateRevoked:
return "The certificate was revoked."
case .certificateSuspended:
return "The certificate was suspended."
case .insufficientCredentials:
return "Insufficient credentials were detected."
case .invalidAction:
return "The action was not valid."
case .invalidAuthority:
return "The authority was not valid."
case .verifyActionFailed:
return "A verify action has failed."
case .invalidCertAuthority:
return "The certificate authority was not valid."
case .invaldCRLAuthority:
return "The CRL authority was not valid."
case .invalidCRLEncoding:
return "The CRL encoding was not valid."
case .invalidCRLType:
return "The CRL type was not valid."
case .invalidCRL:
return "The CRL was not valid."
case .invalidFormType:
return "The form type was not valid."
case .invalidID:
return "The ID was not valid."
case .invalidIdentifier:
return "The identifier was not valid."
case .invalidIndex:
return "The index was not valid."
case .invalidPolicyIdentifiers:
return "The policy identifiers are not valid."
case .invalidTimeString:
return "The time specified was not valid."
case .invalidReason:
return "The trust policy reason was not valid."
case .invalidRequestInputs:
return "The request inputs are not valid."
case .invalidResponseVector:
return "The response vector was not valid."
case .invalidStopOnPolicy:
return "The stop-on policy was not valid."
case .invalidTuple:
return "The tuple was not valid."
case .multipleValuesUnsupported:
return "Multiple values are not supported."
case .notTrusted:
return "The trust policy was not trusted."
case .noDefaultAuthority:
return "No default authority was detected."
case .rejectedForm:
return "The trust policy had a rejected form."
case .requestLost:
return "The request was lost."
case .requestRejected:
return "The request was rejected."
case .unsupportedAddressType:
return "The address type is not supported."
case .unsupportedService:
return "The service is not supported."
case .invalidTupleGroup:
return "The tuple group was not valid."
case .invalidBaseACLs:
return "The base ACLs are not valid."
case .invalidTupleCredendtials:
return "The tuple credentials are not valid."
case .invalidEncoding:
return "The encoding was not valid."
case .invalidValidityPeriod:
return "The validity period was not valid."
case .invalidRequestor:
return "The requestor was not valid."
case .requestDescriptor:
return "The request descriptor was not valid."
case .invalidBundleInfo:
return "The bundle information was not valid."
case .invalidCRLIndex:
return "The CRL index was not valid."
case .noFieldValues:
return "No field values were detected."
case .unsupportedFieldFormat:
return "The field format is not supported."
case .unsupportedIndexInfo:
return "The index information is not supported."
case .unsupportedLocality:
return "The locality is not supported."
case .unsupportedNumAttributes:
return "The number of attributes is not supported."
case .unsupportedNumIndexes:
return "The number of indexes is not supported."
case .unsupportedNumRecordTypes:
return "The number of record types is not supported."
case .fieldSpecifiedMultiple:
return "Too many fields were specified."
case .incompatibleFieldFormat:
return "The field format was incompatible."
case .invalidParsingModule:
return "The parsing module was not valid."
case .databaseLocked:
return "The database is locked."
case .datastoreIsOpen:
return "The data store is open."
case .missingValue:
return "A missing value was detected."
case .unsupportedQueryLimits:
return "The query limits are not supported."
case .unsupportedNumSelectionPreds:
return "The number of selection predicates is not supported."
case .unsupportedOperator:
return "The operator is not supported."
case .invalidDBLocation:
return "The database location is not valid."
case .invalidAccessRequest:
return "The access request is not valid."
case .invalidIndexInfo:
return "The index information is not valid."
case .invalidNewOwner:
return "The new owner is not valid."
case .invalidModifyMode:
return "The modify mode is not valid."
case .missingRequiredExtension:
return "A required certificate extension is missing."
case .extendedKeyUsageNotCritical:
return "The extended key usage extension was not marked critical."
case .timestampMissing:
return "A timestamp was expected but was not found."
case .timestampInvalid:
return "The timestamp was not valid."
case .timestampNotTrusted:
return "The timestamp was not trusted."
case .timestampServiceNotAvailable:
return "The timestamp service is not available."
case .timestampBadAlg:
return "An unrecognized or unsupported Algorithm Identifier in timestamp."
case .timestampBadRequest:
return "The timestamp transaction is not permitted or supported."
case .timestampBadDataFormat:
return "The timestamp data submitted has the wrong format."
case .timestampTimeNotAvailable:
return "The time source for the Timestamp Authority is not available."
case .timestampUnacceptedPolicy:
return "The requested policy is not supported by the Timestamp Authority."
case .timestampUnacceptedExtension:
return "The requested extension is not supported by the Timestamp Authority."
case .timestampAddInfoNotAvailable:
return "The additional information requested is not available."
case .timestampSystemFailure:
return "The timestamp request cannot be handled due to system failure."
case .signingTimeMissing:
return "A signing time was expected but was not found."
case .timestampRejection:
return "A timestamp transaction was rejected."
case .timestampWaiting:
return "A timestamp transaction is waiting."
case .timestampRevocationWarning:
return "A timestamp authority revocation warning was issued."
case .timestampRevocationNotification:
return "A timestamp authority revocation notification was issued."
case .unexpectedError:
return "Unexpected error has occurred."
}
}
}
| mit | a72e79b51e83aeb995d6b8187ca6476c | 46.83057 | 183 | 0.602749 | 5.742318 | false | false | false | false |
grafiti-io/SwiftCharts | SwiftCharts/Views/ChartLinesView.swift | 3 | 3122 | //
// ChartLinesView.swift
// swift_charts
//
// Created by ischuetz on 11/04/15.
// Copyright (c) 2015 ivanschuetz. All rights reserved.
//
import UIKit
public protocol ChartLinesViewPathGenerator {
func generatePath(points: [CGPoint], lineWidth: CGFloat) -> UIBezierPath
}
open class ChartLinesView: UIView {
open let lineColor: UIColor
open let lineWidth: CGFloat
open let lineJoin: LineJoin
open let lineCap: LineCap
open let animDuration: Float
open let animDelay: Float
open let dashPattern: [Double]?
public init(path: UIBezierPath, frame: CGRect, lineColor: UIColor, lineWidth: CGFloat, lineJoin: LineJoin, lineCap: LineCap, animDuration: Float, animDelay: Float, dashPattern: [Double]?) {
self.lineColor = lineColor
self.lineWidth = lineWidth
self.lineJoin = lineJoin
self.lineCap = lineCap
self.animDuration = animDuration
self.animDelay = animDelay
self.dashPattern = dashPattern
super.init(frame: frame)
backgroundColor = UIColor.clear
show(path: path)
}
required public init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
fileprivate func createLineMask(frame: CGRect) -> CALayer {
let lineMaskLayer = CAShapeLayer()
var maskRect = frame
maskRect.origin.y = 0
maskRect.size.height = frame.size.height
let path = CGPath(rect: maskRect, transform: nil)
lineMaskLayer.path = path
return lineMaskLayer
}
open func generateLayer(path: UIBezierPath) -> CAShapeLayer {
let lineLayer = CAShapeLayer()
lineLayer.lineJoin = lineJoin.CALayerString
lineLayer.lineCap = lineCap.CALayerString
lineLayer.fillColor = UIColor.clear.cgColor
lineLayer.lineWidth = lineWidth
lineLayer.path = path.cgPath
lineLayer.strokeColor = lineColor.cgColor
if dashPattern != nil {
lineLayer.lineDashPattern = dashPattern as [NSNumber]?
}
if animDuration > 0 {
lineLayer.strokeEnd = 0.0
let pathAnimation = CABasicAnimation(keyPath: "strokeEnd")
pathAnimation.duration = CFTimeInterval(animDuration)
pathAnimation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut)
pathAnimation.fromValue = NSNumber(value: 0 as Float)
pathAnimation.toValue = NSNumber(value: 1 as Float)
pathAnimation.autoreverses = false
pathAnimation.isRemovedOnCompletion = false
pathAnimation.fillMode = kCAFillModeForwards
pathAnimation.beginTime = CACurrentMediaTime() + CFTimeInterval(animDelay)
lineLayer.add(pathAnimation, forKey: "strokeEndAnimation")
} else {
lineLayer.strokeEnd = 1
}
return lineLayer
}
fileprivate func show(path: UIBezierPath) {
layer.addSublayer(generateLayer(path: path))
}
}
| apache-2.0 | 7e827fdeb7396bd3919c3a0810d903c2 | 32.212766 | 193 | 0.64542 | 5.364261 | false | false | false | false |
algolia/algoliasearch-client-swift | Sources/AlgoliaSearchClient/Models/Places/Country.swift | 1 | 6269 | //
// Country.swift
//
//
// Created by Vladislav Fitc on 12/04/2020.
//
// swiftlint:disable type_body_length
import Foundation
public enum Country: String, Codable {
case afghanistan = "af"
case alandIslands = "ax"
case albania = "al"
case algeria = "dz"
case americanSamoa = "as"
case andorra = "ad"
case angola = "ao"
case anguilla = "ai"
case antarctica = "aq"
case antiguaAndBarbuda = "ag"
case argentina = "ar"
case armenia = "am"
case aruba = "aw"
case australia = "au"
case austria = "at"
case azerbaijan = "az"
case bahamas = "bs"
case bahrain = "bh"
case bangladesh = "bd"
case barbados = "bb"
case belarus = "by"
case belgium = "be"
case belize = "bz"
case benin = "bj"
case bermuda = "bm"
case bhutan = "bt"
case bolivia = "bo"
case caribbeanNetherlands = "bq"
case bosniaAndHerzegovina = "ba"
case botswana = "bw"
case bouvetIsland = "bv"
case brazil = "br"
case britishIndianOceanTerritory = "io"
case bruneiDarussalam = "bn"
case bulgaria = "bg"
case burkinaFaso = "bf"
case burundi = "bi"
case caboVerde = "cv"
case cambodia = "kh"
case cameroon = "cm"
case canada = "ca"
case caymanIslands = "ky"
case centralAfricanRepublic = "cf"
case chad = "td"
case chile = "cl"
case china = "cn"
case christmasIsland = "cx"
case cocosIslands = "cc"
case colombia = "co"
case comoros = "km"
case republicOfTheCongo = "cg"
case democraticRepublicOfTheCongo = "cd"
case cookIslands = "ck"
case costaRica = "cr"
case ivoryCoast = "ci"
case croatia = "hr"
case cuba = "cu"
case curacao = "cw"
case cyprus = "cy"
case czechRepublic = "cz"
case denmark = "dk"
case djibouti = "dj"
case dominica = "dm"
case dominicanRepublic = "do"
case ecuador = "ec"
case egypt = "eg"
case elSalvador = "sv"
case equatorialGuinea = "gq"
case eritrea = "er"
case estonia = "ee"
case eswatini = "sz"
case ethiopia = "et"
case falklandIslands = "fk"
case faroeIslands = "fo"
case fiji = "fj"
case finland = "fi"
case france = "fr"
case frenchGuiana = "gf"
case frenchPolynesia = "pf"
case frenchSouthernAndAntarcticLands = "tf"
case gabon = "ga"
case gambia = "gm"
case georgia = "ge"
case germany = "de"
case ghana = "gh"
case gibraltar = "gi"
case greece = "gr"
case greenland = "gl"
case grenada = "gd"
case guadeloupe = "gp"
case guam = "gu"
case guatemala = "gt"
case bailiwickOfGuernsey = "gg"
case guinea = "gn"
case guineaBissau = "gw"
case guyana = "gy"
case haiti = "ht"
case heardIslandAndMcDonaldIslands = "hm"
case vaticanCity = "va"
case honduras = "hn"
case hongKong = "hk"
case hungary = "hu"
case iceland = "is"
case india = "in"
case indonesia = "id"
case iran = "ir"
case iraq = "iq"
case ireland = "ie"
case isleOfMan = "im"
case israel = "il"
case italy = "it"
case jamaica = "jm"
case japan = "jp"
case jersey = "je"
case jordan = "jo"
case kazakhstan = "kz"
case kenya = "ke"
case kiribati = "ki"
case northKorea = "kp"
case southKorea = "kr"
case kuwait = "kw"
case kyrgyzstan = "kg"
case laos = "la"
case latvia = "lv"
case lebanon = "lb"
case lesotho = "ls"
case liberia = "lr"
case libya = "ly"
case liechtenstein = "li"
case lithuania = "lt"
case luxembourg = "lu"
case macau = "mo"
case madagascar = "mg"
case malawi = "mw"
case malaysia = "my"
case maldives = "mv"
case mali = "ml"
case malta = "mt"
case marshallIslands = "mh"
case martinique = "mq"
case mauritania = "mr"
case mauritius = "mu"
case mayotte = "yt"
case mexico = "mx"
case micronesia = "fm"
case moldova = "md"
case monaco = "mc"
case mongolia = "mn"
case montenegro = "me"
case montserrat = "ms"
case morocco = "ma"
case mozambique = "mz"
case myanmar = "mm"
case namibia = "na"
case nauru = "nr"
case nepal = "np"
case netherlands = "nl"
case newCaledonia = "nc"
case newZealand = "nz"
case nicaragua = "ni"
case niger = "ne"
case nigeria = "ng"
case niue = "nu"
case norfolkIsland = "nf"
case northMacedonia = "mk"
case northernMarianaIslands = "mp"
case norway = "no"
case oman = "om"
case pakistan = "pk"
case palau = "pw"
case palestine = "ps"
case panama = "pa"
case papuaNewGuinea = "pg"
case paraguay = "py"
case peru = "pe"
case philippines = "ph"
case pitcairnIslands = "pn"
case poland = "pl"
case portugal = "pt"
case puertoRico = "pr"
case qatar = "qa"
case reunion = "re"
case romania = "ro"
case russia = "ru"
case rwanda = "rw"
case saintBarthelemy = "bl"
case saintHelena = "sh"
case saintKittsAndNevis = "kn"
case saintLucia = "lc"
case saintMartin = "mf"
case saintPierreAndMiquelon = "pm"
case saintVincentAndTheGrenadines = "vc"
case samoa = "ws"
case sanMarino = "sm"
case saoTomeAndPrincipe = "st"
case saudiArabia = "sa"
case senegal = "sn"
case serbia = "rs"
case seychelles = "sc"
case sierraLeone = "sl"
case singapore = "sg"
case sintMaarten = "sx"
case slovakia = "sk"
case slovenia = "si"
case solomonIslands = "sb"
case somalia = "so"
case southAfrica = "za"
case southGeorgiaAndTheSouthSandwichIslands = "gs"
case southSudan = "ss"
case spain = "es"
case sriLanka = "lk"
case sudan = "sd"
case suriname = "sr"
case svalbardAndJanMayen = "sj"
case sweden = "se"
case switzerland = "ch"
case syria = "sy"
case taiwan = "tw"
case tajikistan = "tj"
case tanzania = "tz"
case thailand = "th"
case timorLeste = "tl"
case togo = "tg"
case tokelau = "tk"
case tonga = "to"
case trinidadAndTobago = "tt"
case tunisia = "tn"
case turkey = "tr"
case turkmenistan = "tm"
case turksAndCaicosIslands = "tc"
case tuvalu = "tv"
case uganda = "ug"
case ukraine = "ua"
case unitedArabEmirates = "ae"
case unitedKingdom = "gb"
case unitedStates = "us"
case unitedStatesMinorOutlyingIslands = "um"
case uruguay = "uy"
case uzbekistan = "uz"
case vanuatu = "vu"
case venezuela = "ve"
case vietnam = "vn"
case virginIslandsGB = "vg"
case virginIslandsUS = "vi"
case wallisAndFutuna = "wf"
case westernSahara = "eh"
case yemen = "ye"
case zambia = "zm"
case zimbabwe = "zw"
}
| mit | 604504e8225a8e6b08f6100add97b40a | 23.019157 | 52 | 0.633594 | 2.625209 | false | false | false | false |
apple/swift-nio | Sources/NIOPerformanceTester/ByteBufferWriteMultipleBenchmarks.swift | 1 | 2653 | //===----------------------------------------------------------------------===//
//
// This source file is part of the SwiftNIO open source project
//
// Copyright (c) 2021 Apple Inc. and the SwiftNIO project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of SwiftNIO project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
import NIOCore
final class ByteBufferReadWriteMultipleIntegersBenchmark<I: FixedWidthInteger>: Benchmark {
private let iterations: Int
private let numberOfInts: Int
private var buffer: ByteBuffer = ByteBuffer()
init(iterations: Int, numberOfInts: Int) {
self.iterations = iterations
self.numberOfInts = numberOfInts
}
func setUp() throws {
self.buffer.reserveCapacity(self.numberOfInts * MemoryLayout<I>.size)
}
func tearDown() {
}
func run() throws -> Int {
var result: I = 0
for _ in 0..<self.iterations {
for i in I(0)..<I(10) {
self.buffer.writeInteger(i)
}
for _ in I(0)..<I(10) {
result = result &+ self.buffer.readInteger(as: I.self)!
}
}
precondition(result == I(self.iterations) * 45)
return self.buffer.readableBytes
}
}
final class ByteBufferMultiReadWriteTenIntegersBenchmark<I: FixedWidthInteger>: Benchmark {
private let iterations: Int
private var buffer: ByteBuffer = ByteBuffer()
init(iterations: Int) {
self.iterations = iterations
}
func setUp() throws {
self.buffer.reserveCapacity(10 * MemoryLayout<I>.size)
}
func tearDown() {
}
func run() throws -> Int {
var result: I = 0
for _ in 0..<self.iterations {
self.buffer.writeMultipleIntegers(
0, 1, 2, 3, 4, 5, 6, 7, 8, 9,
as: (I, I, I, I, I, I, I, I, I, I).self
)
let value = self.buffer.readMultipleIntegers(as: (I, I, I, I, I, I, I, I, I, I).self)!
result = result &+ value.0
result = result &+ value.1
result = result &+ value.2
result = result &+ value.3
result = result &+ value.4
result = result &+ value.5
result = result &+ value.6
result = result &+ value.7
result = result &+ value.8
result = result &+ value.9
}
precondition(result == I(self.iterations) * 45)
return self.buffer.readableBytes
}
}
| apache-2.0 | c184acf7854d58f078c6fc3f2269eb18 | 29.848837 | 98 | 0.542782 | 4.392384 | false | false | false | false |
Candyroot/DesignPattern | state/state/GumballMachine.swift | 1 | 1710 | //
// GumballMachine.swift
// state
//
// Created by Bing Liu on 12/2/14.
// Copyright (c) 2014 UnixOSS. All rights reserved.
//
import Foundation
class GumballMachine {
let soldOutState: State!
let noQuarterState: State!
let hasQuarterState: State!
let soldState: State!
let winnerState: State!
var state: State!
var count = 0
var description: String {
let desc = "\nMighty Gumball, Inc.\n" +
"Swift-enabled Standing Gumball Model #2014\n" +
"Inventory: \(count) gumballs\n"
return count > 0 ? (desc + "Machine is waiting for quarter\n") : (desc + "Machine is sold out")
}
init(numberGumballs: Int) {
soldOutState = SoldOutState(gumballMachine: self)
noQuarterState = NoQuarterState(gumballMachine: self)
hasQuarterState = HasQuarterState(gumballMachine: self)
soldState = SoldState(gumballMachine: self)
winnerState = WinnerState(gumballMachine: self)
count = numberGumballs
if numberGumballs > 0 {
state = noQuarterState
} else {
state = soldOutState
}
}
func insertQuarter() {
state.insertQuarter()
}
func ejectQuarter() {
state.ejectQuarter()
}
func turnCrank() {
state.turnCrank()
state.dispense()
}
func setState(state: State) {
self.state = state
}
func releaseBall() {
println("A gumball comes rolling out the slot...")
if count != 0 {
count--
}
}
func refill(count: Int) {
self.count = count
state = noQuarterState
}
}
| apache-2.0 | e41cf438867dcdccd994c09f411c526f | 22.75 | 103 | 0.573099 | 4.100719 | false | false | false | false |
sora0077/iTunesKit | iTunesKit/src/Endpoint/Lookup.swift | 1 | 5880 | //
// Lookup.swift
// iTunesKit
//
// Created by 林達也 on 2015/10/06.
// Copyright © 2015年 jp.sora0077. All rights reserved.
//
import Foundation
import APIKit
public struct Lookup {
public private(set) var parameters: [String: AnyObject]? = [:]
public init(id: Int, country: String = "US") {
parameters?["id"] = id
parameters?["country"] = country
}
}
extension Lookup: iTunesRequestToken {
public typealias Response = [SearchResult]
public typealias SerializedObject = [String: AnyObject]
public var method: HTTPMethod {
return .GET
}
public var path: String {
return "https://itunes.apple.com/lookup"
}
public func transform(request: NSURLRequest?, response: NSHTTPURLResponse?, object: SerializedObject) throws -> Response {
print(request, object)
return (object["results"] as! [[String: AnyObject]]).map { v in
guard let wrapperType = SearchResultWrapperType(rawValue: v["wrapperType"] as! String) else {
return .Unsupported(v)
}
switch wrapperType {
case .Track:
return .Track(SearchResultTrack(
kind: SearchResultKind(rawValue: v["kind"] as! String)!,
artistId: v["artistId"] as! Int,
collectionId: v["collectionId"] as! Int,
trackId: v["trackId"] as! Int,
artistName: v["artistName"] as! String,
collectionName: v["collectionName"] as! String,
trackName: v["trackName"] as! String,
collectionCensoredName: v["collectionCensoredName"] as! String,
trackCensoredName: v["trackCensoredName"] as! String,
artistViewUrl: v["artistViewUrl"] as! String,
collectionViewUrl: v["collectionViewUrl"] as! String,
trackViewUrl: v["trackViewUrl"] as! String,
previewUrl: v["previewUrl"] as! String,
artworkUrl30: v["artworkUrl30"] as! String,
artworkUrl60: v["artworkUrl60"] as! String,
artworkUrl100: v["artworkUrl100"] as! String,
collectionPrice: v["collectionPrice"] as! Float,
trackPrice: v["trackPrice"] as! Float,
releaseDate: v["releaseDate"] as! String,
collectionExplicitness: v["collectionExplicitness"] as! String,
trackExplicitness: v["trackExplicitness"] as! String,
discCount: v["discCount"] as! Int,
discNumber: v["discNumber"] as! Int,
trackCount: v["trackCount"] as! Int,
trackNumber: v["trackNumber"] as! Int,
trackTimeMillis: v["trackTimeMillis"] as! Int,
country: v["country"] as! String,
currency: v["currency"] as! String,
primaryGenreName: v["primaryGenreName"] as! String,
radioStationUrl: v["radioStationUrl"] as? String,
isStreamable: v["isStreamable"] as! Bool
))
case .Artist:
return .Artist(SearchResultArtist(
artistType: v["artistType"] as! String,
artistName: v["artistName"] as! String,
artistLinkUrl: v["artistLinkUrl"] as! String,
artistId: v["artistId"] as! Int,
amgArtistId: v["amgArtistId"] as? Int,
primaryGenreName: v["primaryGenreName"] as! String,
primaryGenreId: v["primaryGenreId"] as! Int,
radioStationUrl: v["radioStationUrl"] as? String
))
case .Collection:
return .Collection(SearchResultCollection(
collectionType: v["collectionType"] as! String,
artistId: v["artistId"] as! Int,
collectionId: v["collectionId"] as! Int,
amgArtistId: v["amgArtistId"] as! Int,
artistName: v["artistName"] as! String,
collectionName: v["collectionName"] as! String,
collectionCensoredName: v["collectionCensoredName"] as! String,
artistViewUrl: v["artistViewUrl"] as! String,
collectionViewUrl: v["collectionViewUrl"] as! String,
artworkUrl30: v["artworkUrl30"] as! String,
artworkUrl60: v["artworkUrl60"] as! String,
artworkUrl100: v["artworkUrl100"] as! String,
collectionPrice: v["collectionPrice"] as! Float,
collectionExplicitness: v["collectionExplicitness"] as! String,
trackCount: v["trackCount"] as! Int,
copyright: v["copyright"] as! String,
country: v["country"] as! String,
currency: v["currency"] as! String,
releaseDate: v["releaseDate"] as! String,
primaryGenreName: v["primaryGenreName"] as! String,
radioStationUrl: v["radioStationUrl"] as? String
))
}
}
}
}
| mit | 0c427c40bf4d2f0ceda08c467ebe8f51 | 40.638298 | 126 | 0.484756 | 5.342129 | false | false | false | false |
SusanDoggie/Doggie | Sources/DoggieGeometry/ApplePlatform/Geometry/CGAffineTransform.swift | 1 | 2569 | //
// CGAffineTransform.swift
//
// The MIT License
// Copyright (c) 2015 - 2022 Susan Cheng. All rights reserved.
//
// 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.
//
#if os(macOS)
extension AffineTransform {
@inlinable
@inline(__always)
public init(_ transform: SDTransform) {
self.init(
m11: CGFloat(transform.a),
m12: CGFloat(transform.d),
m21: CGFloat(transform.b),
m22: CGFloat(transform.e),
tX: CGFloat(transform.c),
tY: CGFloat(transform.f)
)
}
}
extension SDTransform {
@inlinable
@inline(__always)
public init(_ m: AffineTransform) {
self.a = Double(m.m11)
self.b = Double(m.m21)
self.c = Double(m.tX)
self.d = Double(m.m12)
self.e = Double(m.m22)
self.f = Double(m.tY)
}
}
#endif
#if canImport(CoreGraphics)
extension CGAffineTransform {
@inlinable
@inline(__always)
public init(_ m: SDTransform) {
self.init(
a: CGFloat(m.a),
b: CGFloat(m.d),
c: CGFloat(m.b),
d: CGFloat(m.e),
tx: CGFloat(m.c),
ty: CGFloat(m.f)
)
}
}
extension SDTransform {
@inlinable
@inline(__always)
public init(_ m: CGAffineTransform) {
self.a = Double(m.a)
self.b = Double(m.c)
self.c = Double(m.tx)
self.d = Double(m.b)
self.e = Double(m.d)
self.f = Double(m.ty)
}
}
#endif
| mit | b1f98872ac245f2666d7f65667587b1d | 26.329787 | 81 | 0.619696 | 3.817236 | false | false | false | false |
mohamede1945/quran-ios | Quran/Errors+Description.swift | 2 | 2439 | //
// Errors+Description.swift
// Quran
//
// Created by Mohamed Afifi on 4/28/17.
//
// Quran for iOS is a Quran reading application for iOS.
// Copyright (C) 2017 Quran.com
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
import BatchDownloader
import SQLitePersistence
extension FileSystemError: LocalizedError {
public var errorDescription: String {
let text: String
switch self {
case .unknown:
text = NSLocalizedString("FileSystemError_Unknown", comment: "")
case .noDiskSpace:
text = NSLocalizedString("FileSystemError_NoDiskSpace", comment: "")
}
return text
}
}
extension NetworkError: LocalizedError {
public var errorDescription: String {
let text: String
switch self {
case .unknown:
text = NSLocalizedString("unknown_error_message", comment: "Error description")
case .serverError:
text = NSLocalizedString("unknown_error_message", comment: "Error description")
case .notConnectedToInternet:
text = NSLocalizedString("NetworkError_NotConnectedToInternet", comment: "Error description")
case .internationalRoamingOff:
text = NSLocalizedString("NetworkError_InternationalRoamingOff", comment: "Error description")
case .serverNotReachable:
text = NSLocalizedString("NetworkError_ServerNotReachable", comment: "Error description")
case .connectionLost:
text = NSLocalizedString("NetworkError_ConnectionLost", comment: "Error description")
}
return text
}
}
extension ParsingError: LocalizedError {
public var errorDescription: String {
return NSLocalizedString("NetworkError_Parsing", comment: "When a parsing error occurs")
}
}
extension PersistenceError: LocalizedError {
public var errorDescription: String {
return NSLocalizedString("unknown_error_message", comment: "")
}
}
| gpl-3.0 | 34ce48c352c02ed7070b397223163940 | 34.347826 | 106 | 0.689217 | 5.018519 | false | false | false | false |
jcantosm/coursera.ios | mediaplayer/mediaplayer/ViewController.swift | 1 | 4784 | //
// ViewController.swift
// audioplayer
//
// Created by Javier Cantos on 23/12/15.
// Copyright © 2015 Javier Cantos. All rights reserved.
//
import UIKit
import AVFoundation
class ViewController: UIViewController, UIPickerViewDelegate, UIPickerViewDataSource {
var player : AVAudioPlayer!
var canciones : Array<Array<String>> = Array<Array<String>>()
@IBOutlet weak var uiLabelTitulo: UILabel!
@IBOutlet weak var uiImgPortada: UIImageView!
@IBOutlet weak var uiPickerCanciones: UIPickerView!
@IBOutlet weak var uiControlAudio: UISegmentedControl!
@IBOutlet weak var uiSliderVolumen: UISlider!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
// inicializamos lista de canciones
self.canciones.append(["Amor Es Solo Amar", "PALABRAMUJER.PNG", "AmarEsSoloAmor"])
self.canciones.append(["El Despertar", "ADAGIO.PNG", "ElDespertar"])
self.canciones.append(["Pantera En Libertad", "MONICA4.0.PNG", "PanteraEnLibertad"])
self.canciones.append(["Chicas Malas", "CHICASMALAS.PNG", "ChicasMalas"])
self.canciones.append(["Sobreviviré", "MINAGE.PNG", "Sobrevivire"])
let cancionURL = NSBundle.mainBundle().URLForResource(self.canciones[0][2], withExtension: "mp3")
do {
try self.player = AVAudioPlayer(contentsOfURL: cancionURL!)
// volumen x defecto del reproductor
self.player.volume = self.uiSliderVolumen.value
// mostramos titulo / portada cancion seleccionada
self.uiLabelTitulo.text = self.canciones[0][0]
self.uiImgPortada.image = UIImage(named: "media\(self.canciones[0][1])")
} catch {
print("Error al iniciar reproductor de audio.")
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int {
return 1
}
func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
return self.canciones.count
}
func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
return self.canciones[row][0]
}
func pickerView(pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
let cancionURL = NSBundle.mainBundle().URLForResource(self.canciones[row][2], withExtension: "mp3")
do {
try self.player = AVAudioPlayer(contentsOfURL: cancionURL!)
self.uiControlAudio.selectedSegmentIndex = 0
// mostramos titulo / portada cancion seleccionada
self.uiLabelTitulo.text = self.canciones[row][0]
self.uiImgPortada.image = UIImage(named: self.canciones[row][1])
// empezamos a reproducir la cancion seleccionada
self.player.play()
} catch {
print("Error al iniciar reproductor de audio.")
}
}
@IBAction func changeVolume() {
self.player.volume = self.uiSliderVolumen.value
}
@IBAction func audiocontrol() {
// iniciamos reproduccion de la cancion
if (self.uiControlAudio.selectedSegmentIndex == 0) {
print("play()")
if (self.player != nil && !self.player.playing) {
self.player.play()
}
}
// pausamos reproduccion de la cancion
if (self.uiControlAudio.selectedSegmentIndex == 1) {
print("pause()")
if (self.player != nil && self.player.playing) {
self.player.pause()
}
}
// paramos reproduccion de la cancion
if (self.uiControlAudio.selectedSegmentIndex == 2) {
print("stop()")
if (self.player != nil && self.player.playing) {
self.player.stop()
self.player.currentTime = 0
}
}
// reproducción aleatoria de la cancion
if (self.uiControlAudio.selectedSegmentIndex == 3) {
print("shuffle()")
// numero aleatorio
let random : Int = Int(arc4random() % 5)
// seleccion aleatoria de cancion
self.uiPickerCanciones.selectRow(random, inComponent: 0, animated: true)
self.pickerView(self.uiPickerCanciones, didSelectRow: random, inComponent: 0)
}
}
}
| apache-2.0 | 4c8a1fe9f2fcb247c89e60ad1c585220 | 33.89781 | 109 | 0.59862 | 4.338475 | false | false | false | false |
nshetty26/MH4UDatabase | MH4UDBEngine.swift | 1 | 1999 | //
// MH4UDBEngine.swift
// MH4UDatabase
//
// Created by Neil Shetty on 3/27/15.
// Copyright (c) 2015 GuthuDesigns. All rights reserved.
//
import Foundation
func dbQuery(query : String) -> FMResultSet? {
let mh4uDB = FMDatabase(path: NSBundle.mainBundle().pathForResource("mh4u", ofType: ".db"));
if !mh4uDB.open() {
return nil;
} else {
return mh4uDB.executeQuery(query, withArgumentsInArray: nil);
}
}
func retrieveMonsters(monsterID : Int?) -> NSArray {
var monsterArray: [Monster] = [];
var query : String;
if (monsterID != nil) {
query = "SELECT * FROM Monsters where monsters._id = \(monsterID)";
} else {
query = "SELECT * FROM Monsters";
}
if let s = dbQuery(query) {
while (s.next()) {
var monster = Monster();
monster.monsterID = s.intForColumn("_id");
monster.monsterClass = s.stringForColumn("class");
monster.monsterName = s.stringForColumn("name");
monster.trait = s.stringForColumn("trait")
monster.iconName = s.stringForColumn("icon_name");
monsterArray.append(monster);
}
}
monsterArray.sort({$0.monsterName < $1.monsterName});
return monsterArray;
}
func retrieveMonsterDamageForMonster(monster : Monster) {
var damageArray : [MonsterDamage] = [];
// MonsterDamage *md = [[MonsterDamage alloc] init];
// md.bodyPart = [s stringForColumn:@"body_part"];
// md.cutDamage = [s intForColumn:@"cut"];
// md.impactDamage = [s intForColumn:@"impact"];
// md.shotDamage = [s intForColumn:@"shot"];
// md.fireDamage = [s intForColumn:@"fire"];
// md.waterDamage = [s intForColumn:@"water"];
// md.iceDamage = [s intForColumn:@"ice"];
// md.thunderDamage = md.cutDamage = [s intForColumn:@"thunder"];
// md.dragonDamage = [s intForColumn:@"dragon"];
// md.stun = [s intForColumn:@"ko"];
// [monsterDamageArray addObject:md];
}
| mit | b1f50ceef374ff230a180135008ea547 | 30.730159 | 96 | 0.608304 | 3.641166 | false | false | false | false |
zSOLz/viper-base | ViperBase/ViperBaseTests/Services/ServiceTest.swift | 1 | 4242 | //
// ServiceTest.swift
// ViperBaseTests
//
// Created by SOL on 28.04.17.
// Copyright © 2017 SOL. All rights reserved.
//
import XCTest
@testable import ViperBase
class ServiceTest: XCTestCase {
func testRegisteredInManagerMethod() {
let customService = CustomServiceSubclassMock()
let customManager = ServiceManager(parent: ServiceManager.general)
customManager.register(service: customService)
XCTAssertEqual(CustomServiceMock.registered(inManager: customManager), customService)
ServiceManager.general.register(service: customService)
XCTAssertEqual(CustomServiceMock.registered(), customService)
XCTAssertEqual(CustomServiceMock.registered(inManager: customManager), customService)
customManager.unregister(service: customService)
XCTAssertEqual(CustomServiceMock.registered(), customService)
XCTAssertEqual(CustomServiceMock.registered(inManager: customManager), customService)
ServiceManager.general.unregister(service: customService)
}
func testStartStopMethods() {
let service = CustomServiceMock()
XCTAssertFalse(service.isStarted)
service.start()
XCTAssertTrue(service.isStarted)
service.stop()
XCTAssertFalse(service.isStarted)
}
/*
// Test for this method always fails: Unknown swift compiler bug. Maybe you can solve it :)
func testIsRegisteredInManagerMethod() {
let customSubclassService = CustomServiceMock()
let customManager = ServiceManager(parent: ServiceManager.general)
XCTAssertFalse(CustomServiceMock.isRegistered())
XCTAssertFalse(CustomServiceMock.isRegistered(inManager: customManager))
XCTAssertFalse(CustomServiceSubclassMock.isRegistered())
XCTAssertFalse(CustomServiceSubclassMock.isRegistered(inManager: customManager))
XCTAssertFalse(AnotherCustomServiceMock.isRegistered())
XCTAssertFalse(AnotherCustomServiceMock.isRegistered(inManager: customManager))
customManager.register(service: customSubclassService)
XCTAssertFalse(CustomServiceMock.isRegistered())
XCTAssertTrue(CustomServiceMock.isRegistered(inManager: customManager))
XCTAssertFalse(CustomServiceSubclassMock.isRegistered())
XCTAssertTrue(CustomServiceSubclassMock.isRegistered(inManager: customManager))
XCTAssertFalse(AnotherCustomServiceMock.isRegistered())
XCTAssertFalse(AnotherCustomServiceMock.isRegistered(inManager: customManager))
ServiceManager.general.register(service: customSubclassService)
XCTAssertTrue(CustomServiceMock.isRegistered())
XCTAssertTrue(CustomServiceMock.isRegistered(inManager: customManager))
XCTAssertTrue(CustomServiceSubclassMock.isRegistered())
XCTAssertTrue(CustomServiceSubclassMock.isRegistered(inManager: customManager))
XCTAssertFalse(AnotherCustomServiceMock.isRegistered())
XCTAssertFalse(AnotherCustomServiceMock.isRegistered(inManager: customManager))
customManager.unregister(service: customSubclassService)
XCTAssertTrue(CustomServiceMock.isRegistered())
XCTAssertTrue(CustomServiceMock.isRegistered(inManager: customManager))
XCTAssertTrue(CustomServiceSubclassMock.isRegistered())
XCTAssertTrue(CustomServiceSubclassMock.isRegistered(inManager: customManager))
XCTAssertFalse(AnotherCustomServiceMock.isRegistered())
XCTAssertFalse(AnotherCustomServiceMock.isRegistered(inManager: customManager))
ServiceManager.general.unregister(service: customSubclassService)
XCTAssertFalse(CustomServiceMock.isRegistered())
XCTAssertFalse(CustomServiceMock.isRegistered(inManager: customManager))
XCTAssertFalse(CustomServiceSubclassMock.isRegistered())
XCTAssertFalse(CustomServiceSubclassMock.isRegistered(inManager: customManager))
XCTAssertFalse(AnotherCustomServiceMock.isRegistered())
XCTAssertFalse(AnotherCustomServiceMock.isRegistered(inManager: customManager))
} */
}
| mit | 16871c2c19b3ba9cd2c8a902c6368317 | 44.117021 | 95 | 0.739448 | 5.770068 | false | true | false | false |
systers/PowerUp | Powerup/AppStoreReviewManager.swift | 1 | 1727 | //
// AppStoreReviewManager.swift
// Powerup
import Foundation
import StoreKit
enum AppStoreReviewManager {
static let minimumReviewWorthyActionCount = 4
static func requestReviewIfAppropriate() {
let defaults = UserDefaults.standard
let bundle = Bundle.main
// Read the current number of actions that the user has performed since the last requested review from the User Defaults.
var actionCount = defaults.integer(forKey: .reviewWorthyActionCount)
/* Note: This sample project uses an extension on UserDefaults to eliminate the need for using “stringly” typed keys when accessing values. This is a good practice to follow in order to avoid accidentally mistyping a key as it can cause hard-to-find bugs in your app. You can find this extension in UserDefaults+Key.swift.
*/
actionCount += 1
defaults.set(actionCount, forKey: .reviewWorthyActionCount)
guard actionCount >= minimumReviewWorthyActionCount else {
return
}
let bundleVersionKey = kCFBundleVersionKey as String
let currentVersion = bundle.object(forInfoDictionaryKey: bundleVersionKey) as? String
let lastVersion = defaults.string(forKey: .lastReviewRequestAppVersion)
// Check if this is the first request for this version of the app before continuing.
guard lastVersion == nil || lastVersion != currentVersion else {
return
}
SKStoreReviewController.requestReview()
// Reset the action count and store the current version in User Defaults so that you don’t request again on this version of the app.
defaults.set(0, forKey: .reviewWorthyActionCount)
defaults.set(currentVersion, forKey: .lastReviewRequestAppVersion)
}
}
| gpl-2.0 | f275ecfb4b2ea7c3f66f8eac554bc922 | 33.42 | 325 | 0.74724 | 4.767313 | false | false | false | false |
borisyurkevich/ECAB | ECAB/GameMenuViewController.swift | 1 | 6449 | //
// GameMenuViewController.swift
// ECAB
//
// Created by Boris Yurkevich on 29/05/2021.
// Copyright © 2021 Oliver Braddick and Jan Atkinson. All rights reserved.
//
import UIKit
import os
final class GameMenuViewController: UIViewController {
weak var delelgate: GameMenuDelegate?
@IBOutlet private weak var menuView: MenuView!
@IBOutlet private weak var menuStrip: UIView!
@IBOutlet private weak var backLabel: UILabel!
@IBOutlet private weak var forwardLabel: UILabel!
@IBOutlet private weak var skipLabel: UILabel!
@IBOutlet private weak var pauseLabel: UILabel!
private let borderWidth: CGFloat = 1.0
private let borderColor: CGColor = UIColor.darkGray.cgColor
private var buttonColor: UIColor?
private var activity: UIActivityIndicatorView?
override func viewDidLoad() {
super.viewDidLoad()
addMenuBorders()
setTextColor()
menuView.delegate = self
buttonColor = backLabel.backgroundColor
}
func toggleNavigationButtons(isEnabled: Bool) {
forwardLabel.isEnabled = isEnabled
backLabel.isEnabled = isEnabled
skipLabel.isEnabled = isEnabled
}
func updatePauseButtonState(isHidden: Bool) {
pauseLabel.isHidden = isHidden
}
func updateBackButtonTitle(_ title: String) {
backLabel.text = title
}
func startAnimatingPauseButton() {
pauseLabel.text = ""
activity = UIActivityIndicatorView(style: .medium)
guard let activity = activity else {
return
}
activity.startAnimating()
pauseLabel.addSubview(activity)
activity.translatesAutoresizingMaskIntoConstraints = false
activity.centerYAnchor.constraint(equalTo: pauseLabel.centerYAnchor).isActive = true
activity.centerXAnchor.constraint(equalTo: pauseLabel.centerXAnchor).isActive = true
}
func stopAnimatingPauseButton() {
activity?.removeFromSuperview()
self.pauseLabel.text = "Pause"
self.pauseLabel.textColor = UIColor.label
}
// MARK: - Private
private func addMenuBorders() {
backLabel.layer.borderWidth = borderWidth
backLabel.layer.borderColor = borderColor
forwardLabel.layer.borderWidth = borderWidth
forwardLabel.layer.borderColor = borderColor
skipLabel.layer.borderWidth = borderWidth
skipLabel.layer.borderColor = borderColor
pauseLabel.layer.borderWidth = borderWidth
pauseLabel.layer.borderColor = borderColor
}
private func setTextColor() {
backLabel.textColor = UIColor.label
forwardLabel.textColor = UIColor.label
skipLabel.textColor = UIColor.label
pauseLabel.textColor = UIColor.label
}
}
extension GameMenuViewController: MenuViewDelegate {
func reset(location: CGPoint) {
DispatchQueue.main.async { [unowned self] in
if location.x < forwardLabel.frame.origin.x {
backLabel.backgroundColor = buttonColor
backLabel.textColor = UIColor.label
} else if location.x < skipLabel.frame.origin.x {
forwardLabel.backgroundColor = buttonColor
forwardLabel.textColor = UIColor.label
} else if location.x <= skipLabel.frame.origin.x + skipLabel.frame.width {
skipLabel.backgroundColor = buttonColor
skipLabel.textColor = UIColor.label
} else if location.x >= pauseLabel.frame.origin.x {
pauseLabel.backgroundColor = buttonColor
pauseLabel.textColor = UIColor.label
} else {
os_log(.debug, "touch outise buttons area: %@", location.debugDescription)
}
}
}
func highlight(location: CGPoint) {
DispatchQueue.main.async { [unowned self] in
if location.x < forwardLabel.frame.origin.x {
if backLabel.isEnabled {
backLabel.backgroundColor = view.tintColor
backLabel.textColor = UIColor.lightText
}
} else if location.x < skipLabel.frame.origin.x {
if forwardLabel.isEnabled {
forwardLabel.backgroundColor = view.tintColor
forwardLabel.textColor = UIColor.lightText
}
} else if location.x <= skipLabel.frame.origin.x + skipLabel.frame.width {
if skipLabel.isEnabled {
skipLabel.backgroundColor = view.tintColor
skipLabel.textColor = UIColor.lightText
}
} else if location.x >= pauseLabel.frame.origin.x {
if pauseLabel.isEnabled {
pauseLabel.backgroundColor = view.tintColor
pauseLabel.textColor = UIColor.lightText
}
} else {
os_log(.debug, "touch outise buttons area: %@", location.debugDescription)
}
}
}
func handleTouch(location: CGPoint) {
DispatchQueue.main.async { [unowned self] in
if location.x < forwardLabel.frame.origin.x {
if backLabel.isEnabled {
backLabel.backgroundColor = buttonColor
backLabel.textColor = UIColor.label
delelgate?.presentPreviousScreen()
}
} else if location.x < skipLabel.frame.origin.x {
if forwardLabel.isEnabled {
forwardLabel.backgroundColor = buttonColor
forwardLabel.textColor = UIColor.label
delelgate?.presentNextScreen()
}
} else if location.x <= skipLabel.frame.origin.x + skipLabel.frame.width {
if skipLabel.isEnabled {
skipLabel.backgroundColor = buttonColor
skipLabel.textColor = UIColor.label
delelgate?.skip()
}
} else if location.x >= pauseLabel.frame.origin.x {
if pauseLabel.isEnabled {
pauseLabel.backgroundColor = buttonColor
pauseLabel.textColor = UIColor.label
delelgate?.presentPause()
}
} else {
os_log(.debug, "touch outise buttons area: %@", location.debugDescription)
}
}
}
}
| mit | 7f5ba15f1df1c13278cab622e3b2e468 | 33.481283 | 92 | 0.606855 | 5.3868 | false | false | false | false |
roecrew/AudioKit | Examples/iOS/AnalogSynthX/AnalogSynthX/CustomControls/KnobLarge.swift | 1 | 2441 | //
// KnobLarge.swift
// Swift Synth
//
// Created by Matthew Fecher on 1/8/16.
// Copyright © 2016 AudioKit. All rights reserved.
//
import UIKit
protocol KnobLargeDelegate {
func updateKnobValue(value: Double, tag: Int)
}
@IBDesignable
class KnobLarge: Knob {
var delegate: KnobLargeDelegate?
// Image Declarations
var knob212_base = UIImage(named: "knob212_base")
var knob212_indicator = UIImage(named: "knob212_indicator")
override func drawRect(rect: CGRect) {
drawKnobLarge(knobValue: knobValue)
}
// MARK: - Set Percentages
override func setPercentagesWithTouchPoint(touchPoint: CGPoint) {
super.setPercentagesWithTouchPoint(touchPoint)
delegate?.updateKnobValue(value, tag: self.tag)
setNeedsDisplay()
}
// MARK: - PaintCode generated code
func drawKnobLarge(knobValue knobValue: CGFloat = 0.332) {
//// General Declarations
let context = UIGraphicsGetCurrentContext()
//// Variable Declarations
let knobAngle: CGFloat = -240 * knobValue
//// Picture Drawing
let picturePath = UIBezierPath(rect: CGRect(x: 10, y: 10, width: 106, height: 106))
CGContextSaveGState(context)
picturePath.addClip()
knob212_base!.drawInRect(CGRectMake(10, 10, knob212_base!.size.width, knob212_base!.size.height))
CGContextRestoreGState(context)
//// Picture 2 Drawing
CGContextSaveGState(context)
CGContextTranslateCTM(context, 63, 63)
CGContextRotateCTM(context, -(knobAngle + 120) * CGFloat(M_PI) / 180)
let picture2Path = UIBezierPath(rect: CGRect(x: -53, y: -53, width: 106, height: 106))
CGContextSaveGState(context)
picture2Path.addClip()
knob212_indicator!.drawInRect(CGRectMake(-53, -53, knob212_indicator!.size.width, knob212_indicator!.size.height))
CGContextRestoreGState(context)
CGContextRestoreGState(context)
}
// MARK: - Allow knobs to appear in IB
override func prepareForInterfaceBuilder() {
super.prepareForInterfaceBuilder()
let bundle = NSBundle(forClass: self.dynamicType)
knob212_base = UIImage(named: "knob212_base", inBundle: bundle, compatibleWithTraitCollection: self.traitCollection)!
knob212_indicator = UIImage(named: "knob212_indicator", inBundle: bundle, compatibleWithTraitCollection: self.traitCollection)!
}
}
| mit | b3ac74e0cc7867f3f6b538f3f4239f75 | 32.424658 | 135 | 0.683607 | 4.436364 | false | false | false | false |
maxvol/RxCloudKit | RxCloudKit/RecordFetcher.swift | 1 | 1552 | //
// Fetcher.swift
// RxCloudKit
//
// Created by Maxim Volgin on 22/06/2017.
// Copyright (c) RxSwiftCommunity. All rights reserved.
//
import RxSwift
import CloudKit
@available(iOS 10, *)
final class RecordFetcher {
typealias Observer = AnyObserver<CKRecord>
private let observer: Observer
private let database: CKDatabase
private let limit: Int
init(observer: Observer, database: CKDatabase, query: CKQuery, limit: Int) {
self.observer = observer
self.database = database
self.limit = limit
self.fetch(query: query)
}
private func recordFetchedBlock(record: CKRecord) {
self.observer.on(.next(record))
}
private func queryCompletionBlock(cursor: CKQueryOperation.Cursor?, error: Error?) {
if let error = error {
observer.on(.error(error))
return
}
if let cursor = cursor {
let operation = CKQueryOperation(cursor: cursor)
self.setupAndAdd(operation: operation)
return
}
observer.on(.completed)
}
private func fetch(query: CKQuery) {
let operation = CKQueryOperation(query: query)
self.setupAndAdd(operation: operation)
}
private func setupAndAdd(operation: CKQueryOperation) {
operation.resultsLimit = self.limit
operation.recordFetchedBlock = self.recordFetchedBlock
operation.queryCompletionBlock = self.queryCompletionBlock
self.database.add(operation)
}
}
| mit | f234e79f4fa1aa385da2c61e8a96b3cf | 25.305085 | 88 | 0.639175 | 4.632836 | false | false | false | false |
GrandCentralBoard/GrandCentralBoard | Pods/Operations/Sources/Features/Shared/CloudKitOperation.swift | 2 | 13647 | //
// CloudKitOperation.swift
// Operations
//
// Created by Daniel Thorpe on 22/07/2015.
// Copyright (c) 2015 Daniel Thorpe. All rights reserved.
//
import Foundation
import CloudKit
// MARK: - OPRCKOperation
public class OPRCKOperation<T where T: NSOperation, T: CKOperationType>: ReachableOperation<T> {
override init(_ operation: T, connectivity: Reachability.Connectivity = .AnyConnectionKind) {
super.init(operation, connectivity: connectivity)
name = "OPRCKOperation<\(T.self)>"
}
}
// MARK: - Cloud Kit Error Recovery
public class CloudKitRecovery<T where T: NSOperation, T: CKOperationType> {
public typealias V = OPRCKOperation<T>
public typealias ErrorResponse = (delay: Delay?, configure: V -> Void)
public typealias Handler = (error: NSError, log: LoggerType, suggested: ErrorResponse) -> ErrorResponse?
typealias Payload = (Delay?, V)
var defaultHandlers: [CKErrorCode: Handler]
var customHandlers: [CKErrorCode: Handler]
init() {
defaultHandlers = [:]
customHandlers = [:]
addDefaultHandlers()
}
internal func recoverWithInfo(info: RetryFailureInfo<V>, payload: Payload) -> ErrorResponse? {
guard let (code, error) = cloudKitErrorsFromInfo(info) else { return .None }
// We take the payload, if not nil, and return the delay, and configuration block
let suggestion: ErrorResponse = (payload.0, info.configure )
var response: ErrorResponse? = .None
response = defaultHandlers[code]?(error: error, log: info.log, suggested: suggestion)
response = customHandlers[code]?(error: error, log: info.log, suggested: response ?? suggestion)
return response
// 5. Consider how we might pass the result of the default into the custom
}
func addDefaultHandlers() {
let exit: Handler = { error, log, _ in
log.fatal("Exiting due to CloudKit Error: \(error)")
return .None
}
let retry: Handler = { error, log, suggestion in
if let interval = (error.userInfo[CKErrorRetryAfterKey] as? NSNumber).map({ $0.doubleValue }) {
return (Delay.By(interval), suggestion.configure)
}
return suggestion
}
setDefaultHandlerForCode(.InternalError, handler: exit)
setDefaultHandlerForCode(.MissingEntitlement, handler: exit)
setDefaultHandlerForCode(.InvalidArguments, handler: exit)
setDefaultHandlerForCode(.ServerRejectedRequest, handler: exit)
setDefaultHandlerForCode(.AssetFileNotFound, handler: exit)
setDefaultHandlerForCode(.IncompatibleVersion, handler: exit)
setDefaultHandlerForCode(.ConstraintViolation, handler: exit)
setDefaultHandlerForCode(.BadDatabase, handler: exit)
setDefaultHandlerForCode(.QuotaExceeded, handler: exit)
setDefaultHandlerForCode(.OperationCancelled, handler: exit)
setDefaultHandlerForCode(.NetworkUnavailable, handler: retry)
setDefaultHandlerForCode(.NetworkFailure, handler: retry)
setDefaultHandlerForCode(.ServiceUnavailable, handler: retry)
setDefaultHandlerForCode(.RequestRateLimited, handler: retry)
setDefaultHandlerForCode(.AssetFileModified, handler: retry)
setDefaultHandlerForCode(.BatchRequestFailed, handler: retry)
setDefaultHandlerForCode(.ZoneBusy, handler: retry)
}
func setDefaultHandlerForCode(code: CKErrorCode, handler: Handler) {
defaultHandlers.updateValue(handler, forKey: code)
}
func setCustomHandlerForCode(code: CKErrorCode, handler: Handler) {
customHandlers.updateValue(handler, forKey: code)
}
internal func cloudKitErrorsFromInfo(info: RetryFailureInfo<OPRCKOperation<T>>) -> (code: CKErrorCode, error: NSError)? {
let mapped: [(CKErrorCode, NSError)] = info.errors.flatMap { error in
let error = error as NSError
if error.domain == CKErrorDomain, let code = CKErrorCode(rawValue: error.code) {
return (code, error)
}
return .None
}
return mapped.first
}
}
// MARK: - CloudKitOperation
/**
# CloudKitOperation
CloudKitOperation is a generic operation which can be used to configure and schedule
the execution of Apple's CKOperation subclasses.
## Generics
CloudKitOperation is generic over the type of the CKOperation. See Apple's documentation
on their CloudKit NSOperation classes.
## Initialization
CloudKitOperation is initialized with a block which should return an instance of the
required operation. Note that some CKOperation subclasses have static methods to
return standard instances. Given Swift's treatment of trailing closure arguments, this
means that the following is a standard initialization pattern:
```swift
let operation = CloudKitOperation { CKFetchRecordZonesOperation.fetchAllRecordZonesOperation() }
```
This works because, the initializer only takes a trailing closure. The closure receives no arguments
and is only one line, so the return is not needed.
## Configuration
Most CKOperation subclasses need various properties setting before they are added to a queue. Sometimes
these can be done via their initializers. However, it is also possible to set the properties directly.
This can be done directly onto the CloudKitOperation. For example, given the above:
```swift
let container = CKContainer.defaultContainer()
operation.container = container
operation.database = container.privateCloudDatabase
```
This will set the container and the database through the CloudKitOperation into the wrapped CKOperation
instance.
## Completion
All CKOperation subclasses have a completion block which should be set. This completion block receives
the "results" of the operation, and an `NSError` argument. However, CloudKitOperation features its own
semi-automatic error handling system. Therefore, the only completion block needed is one which receives
the "results". Essentially, all that is needed is to manage the happy path of the operation. For all
CKOperation subclasses, this can be configured directly on the CloudKitOperation instance, using a
pattern of `setOperationKindCompletionBlock { }`. For example, given the above:
```swift
operation.setFetchRecordZonesCompletionBlock { zonesByID in
// Do something with the zonesByID
}
```
Note, that for the automatic error handling to kick in, the happy path must be set (as above).
### Error Handling
When the completion block is set as above, any errors receives from the CKOperation subclass are
intercepted, and instead of the provided block being executed, the operation finsihes with an error.
However, CloudKitOperation is a subclass of RetryOperation, which is actually a GroupOperation subclass,
and when a child operation finishes with an error, RetryOperation will consult its error handler, and
attempt to retry the operation.
In the case of CloudKitOperation, the error handler, which is configured internally has automatic
support for many common error kinds. When the CKOperation receives an error, the CKErrorCode is extracted,
and the handler consults a CloudKitRecovery instance to check for a particular way to handle that error
code. In some cases, this will result in a tuple being returned. The tuple is an optional Delay, and
a new instance of the CKOperation class.
This is why the initializer takes a block which returns an instance of the CKOperation subclass, rather
than just an instance directly. In addition, any configuration set on the operation is captured and
applied again to new instances of the CKOperation subclass.
The delay is used to automatically respect any wait periods returned in the CloudKit NSError object. If
none are given, a random time delay between 0.1 and 1.0 seconds is used.
If the error recovery does not have a handler, or the handler returns nil (no tuple), the CloudKitOperation
will finish (with the errors).
### Custom Error Handling
To provide bespoke error handling, further configure the CloudKitOperation by calling setErrorHandlerForCode.
For example:
```swift
operation.setErrorHandlerForCode(.PartialFailure) { error, log, suggested in
return suggested
}
```
Note that the error handler receives the received error, a logger object, and the suggested tuple, which
could be modified before being returned. Alternatively, return nil to not retry.
*/
public final class CloudKitOperation<T where T: NSOperation, T: CKOperationType>: RetryOperation<OPRCKOperation<T>> {
public typealias ErrorHandler = CloudKitRecovery<T>.Handler
let recovery: CloudKitRecovery<T>
var operation: T {
return current.operation
}
public convenience init(_ body: () -> T?) {
self.init(generator: AnyGenerator(body: body), connectivity: .AnyConnectionKind, reachability: ReachabilityManager(DeviceReachability()))
}
convenience init(connectivity: Reachability.Connectivity = .AnyConnectionKind, reachability: SystemReachabilityType, _ body: () -> T?) {
self.init(generator: AnyGenerator(body: body), connectivity: .AnyConnectionKind, reachability: reachability)
}
init<G where G: GeneratorType, G.Element == T>(generator gen: G, connectivity: Reachability.Connectivity = .AnyConnectionKind, reachability: SystemReachabilityType) {
// Creates a standard random delay between retries
let strategy: WaitStrategy = .Random((0.1, 1.0))
let delay = MapGenerator(strategy.generator()) { Delay.By($0) }
// Maps the generator to wrap the target operation.
let generator = MapGenerator(gen) { operation -> OPRCKOperation<T> in
let op = OPRCKOperation(operation, connectivity: connectivity)
op.reachability = reachability
return op
}
// Creates a CloudKitRecovery object
let _recovery = CloudKitRecovery<T>()
// Creates a Retry Handler using the recovery object
let handler: Handler = { info, payload in
guard let (delay, configure) = _recovery.recoverWithInfo(info, payload: payload) else { return .None }
let (_, operation) = payload
configure(operation)
return (delay, operation)
}
recovery = _recovery
super.init(delay: delay, generator: generator, retry: handler)
name = "CloudKitOperation<\(T.self)>"
}
public func setErrorHandlerForCode(code: CKErrorCode, handler: ErrorHandler) {
recovery.setCustomHandlerForCode(code, handler: handler)
}
override func childOperation(child: NSOperation, didFinishWithErrors errors: [ErrorType]) {
if !(child is OPRCKOperation<T>) {
super.childOperation(child, didFinishWithErrors: errors)
}
}
}
// MARK: - BatchedCloudKitOperation
class CloudKitOperationGenerator<T where T: NSOperation, T: CKOperationType>: GeneratorType {
let connectivity: Reachability.Connectivity
let reachability: SystemReachabilityType
var generator: AnyGenerator<T>
var more: Bool = true
init<G where G: GeneratorType, G.Element == T>(generator: G, connectivity: Reachability.Connectivity = .AnyConnectionKind, reachability: SystemReachabilityType) {
self.generator = AnyGenerator(generator)
self.connectivity = connectivity
self.reachability = reachability
}
func next() -> CloudKitOperation<T>? {
guard more else { return .None }
return CloudKitOperation(generator: generator, connectivity: connectivity, reachability: reachability)
}
}
public class BatchedCloudKitOperation<T where T: NSOperation, T: CKBatchedOperationType>: RepeatedOperation<CloudKitOperation<T>> {
public var enableBatchProcessing: Bool
var generator: CloudKitOperationGenerator<T>
public var operation: T {
return current.operation
}
public convenience init(enableBatchProcessing enable: Bool = true, _ body: () -> T?) {
self.init(generator: AnyGenerator(body: body), enableBatchProcessing: enable, connectivity: .AnyConnectionKind, reachability: ReachabilityManager(DeviceReachability()))
}
convenience init(enableBatchProcessing enable: Bool = true, connectivity: Reachability.Connectivity = .AnyConnectionKind, reachability: SystemReachabilityType, _ body: () -> T?) {
self.init(generator: AnyGenerator(body: body), enableBatchProcessing: enable, connectivity: connectivity, reachability: reachability)
}
init<G where G: GeneratorType, G.Element == T>(generator gen: G, enableBatchProcessing enable: Bool = true, connectivity: Reachability.Connectivity = .AnyConnectionKind, reachability: SystemReachabilityType) {
enableBatchProcessing = enable
generator = CloudKitOperationGenerator(generator: gen, connectivity: connectivity, reachability: reachability)
// Creates a standard fixed delay between batches (not reties)
let strategy: WaitStrategy = .Fixed(0.1)
let delay = MapGenerator(strategy.generator()) { Delay.By($0) }
let tuple = TupleGenerator(primary: generator, secondary: delay)
super.init(generator: AnyGenerator(tuple))
}
public override func willFinishOperation(operation: NSOperation, withErrors errors: [ErrorType]) {
if errors.isEmpty, let cloudKitOperation = operation as? CloudKitOperation<T> {
generator.more = enableBatchProcessing && cloudKitOperation.current.moreComing
}
super.willFinishOperation(operation, withErrors: errors)
}
}
| gpl-3.0 | e8ef72056c3517eabe3cb2116d9d81bf | 40.990769 | 213 | 0.726826 | 4.853129 | false | false | false | false |
a736220388/FinestFood | FinestFood/FinestFood/classes/common/Constant.swift | 1 | 4139 | //
// Constant.swift
// FinestFood
//
// Created by qianfeng on 16/8/15.
// Copyright © 2016年 qianfeng. All rights reserved.
//
import UIKit
public let kScreenWidth = UIScreen.mainScreen().bounds.width
public let kScreenHeight = UIScreen.mainScreen().bounds.height
public let FSScrollViewUrl = "http://api.guozhoumoapp.com/v1/banners?channel=iOS"
//专题集合(体验课...)
public let FSScrollViewListlUrl = "http://api.guozhoumoapp.com/v1/collections/%d/posts?gender=%d&generation=%d&limit=%d&offset=%d"
public let FSSearchWordUrl = "http://api.guozhoumoapp.com/v1/search/hot_words"
public let FSSearchItemResultUrl = "http://api.guozhoumoapp.com/v1/search/item?keyword=%@&limit=%d&offset=%d&sort="
public let FSSearchPostResultUrl = "http://api.guozhoumoapp.com/v1/search/post?keyword=%@&limit=%d&offset=%d&sort="
public let FSFoodListUrl = "http://api.guozhoumoapp.com/v1/channels/2/items?gender=%d&generation=%d&limit=%d&offset=%d"
//宅家
public let FSFoodMoreListUrl = "http://api.guozhoumoapp.com/v1/channels/%d/items?limit=%d&offset=%d"
public let FSFoodDetailUrl = "http://api.guozhoumoapp.com/v1/posts/%d"
public let FLFoodListUrl = "http://api.guozhoumoapp.com/v2/items?gender=%d&generation=%d&limit=%d&offset=%d"
public let FLFoodDetailUrl = "http://api.guozhoumoapp.com/v2/items/%d/comments?limit=%d&offset=%d"//单品中商品的detail
public let FLFoodSearchDetailUrl = "http://api.guozhoumoapp.com/v2/items/%d"//搜索中商品的detail
public let CGHomeOutUrl = "http://api.guozhoumoapp.com/v1/channel_groups/all"
//查看全部
public let CGSubjectUrl = "http://api.guozhoumoapp.com/v1/collections?limit=%d&offset=%d"
//登录
public let MineLoginUrl = "http://api.guozhoumoapp.com/v1/account/signin"
//postBody:mobile=18550217023&password=123456
//登陆后获取用户信息
public let UserInfoPostUrl = "http://api.guozhoumoapp.com/v1/users/me/post_likes?limit==%d&offset=%d"
public let UserInfoListUrl = "http://api.guozhoumoapp.com/v1/users/me/favorite_lists?limit==%d&offset=%d"
//注册
public let MineRegisterUrl = "http://api.guozhoumoapp.com/v1/account/mobile_exist"
//post:mobile=18550217032
//{
// "code": 200,
// "data": {
// "exist": false
// },
// "message": "OK"
//}
//http://api.guozhoumoapp.com/v1/account/sms_token
// {
// "code": 200,
// "data": {
// "token": "xwg6e9f6z5"
// },
// "message": "OK"
//}
//http://api.guozhoumoapp.com/v1/account/send_verification_code
//access_token=I7iUQTM%2Bbmpucs6rWeMAAMoCFx4%3D&mobile=18550217032
// {
// "code": 200,
// "data": {},
// "message": "OK"
//}
/*
精选
滚动视图
http://api.guozhoumoapp.com/v1/banners?channel=iOS
滚动视图详情
1,体验课:http://api.guozhoumoapp.com/v1/collections/4/posts?gender=1&generation=0&limit=20&offset=0
2,下厨房:http://api.guozhoumoapp.com/v1/collections/3/posts?gender=1&generation=0&limit=20&offset=0
3,来一发:http://api.guozhoumoapp.com/v1/collections/1/posts?gender=1&generation=0&limit=20&offset=0
4,周末宅家:http://api.guozhoumoapp.com/v1/collections/2/posts?gender=1&generation=0&limit=20&offset=0
内容
http://api.guozhoumoapp.com/v1/channels/2/items?gender=1&generation=0&limit=20&offset=0
搜索
http://api.guozhoumoapp.com/v1/search/hot_words?
商品:http://api.guozhoumoapp.com/v1/search/item?keyword=%E6%89%8B%E5%B7%A5&limit=20&offset=0&sort=
攻略:http://api.guozhoumoapp.com/v1/search/post?keyword=%E4%B8%8A%E6%B5%B7&limit=20&offset=0&sort=
周末逛店
内容:http://api.guozhoumoapp.com/v1/channels/12/items?limit=20&offset=0
尝美食
内容:http://api.guozhoumoapp.com/v1/channels/15/items?limit=20&offset=0
体验课
内容:http://api.guozhoumoapp.com/v1/channels/13/items?limit=20&offset=0
周边游
内容:http://api.guozhoumoapp.com/v1/channels/14/items?limit=20&offset=0
单品
内容:http://api.guozhoumoapp.com/v2/items?gender=1&generation=0&limit=20&offset=0
宅家,出门 http://api.guozhoumoapp.com/v1/channel_groups/all
专题集合 http://api.guozhoumoapp.com/v1/collections?limit=6&offset=0
*/ | mit | dc13406f8f9366e163b2e8d33caba2b5 | 33.769912 | 130 | 0.715631 | 2.430693 | false | false | false | false |
apple/swift-corelibs-foundation | Darwin/Foundation-swiftoverlay/NSExpression.swift | 1 | 1045 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2020 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
//
//===----------------------------------------------------------------------===//
@_exported import Foundation // Clang module
extension NSExpression {
// + (NSExpression *) expressionWithFormat:(NSString *)expressionFormat, ...;
public
convenience init(format expressionFormat: __shared String, _ args: CVarArg...) {
let va_args = getVaList(args)
self.init(format: expressionFormat, arguments: va_args)
}
}
extension NSExpression {
public convenience init<Root, Value>(forKeyPath keyPath: KeyPath<Root, Value>) {
self.init(forKeyPath: _bridgeKeyPathToString(keyPath))
}
}
| apache-2.0 | 9cc3c18e7976e200b4bae38f606ace79 | 36.321429 | 84 | 0.613397 | 4.929245 | false | false | false | false |
jbourjeli/SwiftLabelPhoto | Photos++/FontAwesomeService.swift | 1 | 6836 | //
// FontAwesomeService.swift
// Photos++
//
// Created by Joseph Bourjeli on 9/23/16.
// Copyright © 2016 WorkSmarterComputing. All rights reserved.
//
import UIKit
import CoreText
public enum FontAwesomeIcon: String{
case faCheck="\u{f00c}"
case faCheckSquareO="\u{f046}"
case faMoney="\u{f0d6}"
case faCC="\u{f09d}"
case faCCAmex="\u{f1f3}"
case faCCDiscover="\u{f1f2}"
case faCCMastercard="\u{f1f1}"
case faCCVisa="\u{f1f0}"
case faBuilding="\u{f1ad}"
case faHome="\u{f015}"
case faCar="\u{f1b9}"
case faEnvelope="\u{f0e0}"
case faEnvelopeO="\u{f003}"
case faPhone="\u{f095}"
case faExternalLink="\u{f08e}"
case faBan="\u{f05e}"
case faTable="\u{f0ce}"
case faRepeat="\u{f01e}"
case faMinusCircle="\u{f056}"
case faTrashO="\u{f014}"
case faArchive="\u{f187}"
case faEllipsisV="\u{f142}"
case faEllipsisH="\u{f141}"
case faFilter="\u{f0b0}"
case faPencil="\u{f040}"
case faCameraRetro="\u{f083}"
case faShareSquareO="\u{f045}"
case faShareAlt="\u{f1e0}"
case faShare="\u{f064}"
case faStar="\u{f005}"
case faHandPaperO="\u{f256}"
case faExclamationTriangle="\u{f071}"
case faThumbsOUp="\u{f087}"
case faPlus="\u{f067}"
case faFolderOpen="\u{f07c}"
case faUser="\u{f007}"
case faSunO="\u{f185}"
case faCloud="\u{f0c2}"
case faBook="\u{f02d}"
case faCog="\u{f013}"
case faCogs="\u{f085}"
case faGavel="\u{f0e3}"
case faVolumeUp="\u{f028}"
case faBars="\u{f0c9}"
case faBarChart="\u{f080}"
case faCommentO="\u{f0e5}"
case faCommentsO="\u{f0e6}"
case faTag="\u{f02b}"
;
}
public class FontAwesome {
let icon: FontAwesomeIcon
var textColor: UIColor {
didSet {
self.renderedImage = nil
}
}
var size: CGSize {
didSet {
self.renderedImage = nil
}
}
private var renderedImage: UIImage?
public init(_ icon: FontAwesomeIcon) {
self.icon = icon
self.textColor = UIColor.black
self.size = CGSize(width: 10, height: 10)
}
public convenience init(_ icon: FontAwesomeIcon, textColor: UIColor, size: CGSize) {
self.init(icon)
self.textColor = textColor
self.size = size
}
public convenience init(_ icon: FontAwesomeIcon, size: CGSize) {
self.init(icon)
self.size = size
}
public func image() -> UIImage {
if let renderedImage = self.renderedImage {
return renderedImage
}
let paragraph = NSMutableParagraphStyle()
paragraph.alignment = NSTextAlignment.center
// Taken from FontAwesome.io's Fixed Width Icon CSS
let fontAspectRatio: CGFloat = 1.28571429
let fontSize = min(self.size.width / fontAspectRatio, self.size.height)
let attributedString = NSAttributedString(
string: self.icon.rawValue as String,
attributes: [NSFontAttributeName: UIFont.fontAwesomeOfSize(fontSize: fontSize)!,
NSForegroundColorAttributeName: self.textColor,
NSParagraphStyleAttributeName: paragraph])
UIGraphicsBeginImageContextWithOptions(self.size, false , 0.0)
let boundingRect = CGRect(x:0,
y:(self.size.height - fontSize) / 2,
width:self.size.width,
height:fontSize)
attributedString.draw(in: boundingRect)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
self.renderedImage = image
return image!
}
}
public class FontAwesomeUtils {
public static let smallFont = UIFont.fontAwesomeOfSize(fontSize: 12)
public static let regularFont = UIFont.fontAwesomeOfSize(fontSize: 16)
public static let bigFont = UIFont.fontAwesomeOfSize(fontSize: 20)
}
public extension UIImage {
public static func imageFromfontAwesomeIcon(name: FontAwesomeIcon, withTextColor textColor: UIColor, ofSize size: CGSize) -> UIImage {
let paragraph = NSMutableParagraphStyle()
paragraph.alignment = NSTextAlignment.center
// Taken from FontAwesome.io's Fixed Width Icon CSS
let fontAspectRatio: CGFloat = 1.28571429
let fontSize = min(size.width / fontAspectRatio, size.height)
let attributedString = NSAttributedString(string: name.rawValue as String,
attributes: [NSFontAttributeName: UIFont.fontAwesomeOfSize(fontSize: fontSize)!,
NSForegroundColorAttributeName: textColor,
NSParagraphStyleAttributeName: paragraph])
UIGraphicsBeginImageContextWithOptions(size, false , 0.0)
attributedString.draw(in: CGRect(x:0, y:(size.height - fontSize) / 2,
width: size.width, height:fontSize))
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image!
}
}
public extension UIFont {
public static func fontAwesomeOfSize(fontSize: CGFloat) -> UIFont? {
let name = "FontAwesome"
if (UIFont.fontNames(forFamilyName: name).isEmpty ) {
FontLoader.loadFont(name: name)
}
return UIFont(name: name, size: fontSize)
}
}
private class FontLoader {
class func loadFont(name: String) {
let bundle = Bundle(for: FontLoader.self)
var fontURL: URL
let identifier = bundle.bundleIdentifier
if identifier?.hasPrefix("org.cocoapods") == true {
// If this framework is added using CocoaPods, resources is placed under a subdirectory
fontURL = bundle.url(forResource: name, withExtension: "otf", subdirectory: "FontAwesome.swift.bundle")! as URL
} else {
fontURL = bundle.url(forResource: name, withExtension: "otf")! as URL
}
let data = NSData(contentsOf: fontURL as URL)!
let provider = CGDataProvider(data: data)
let font = CGFont(provider!)
var error: Unmanaged<CFError>?
if !CTFontManagerRegisterGraphicsFont(font, &error) {
let errorDescription: CFString = CFErrorCopyDescription(error!.takeUnretainedValue())
let nsError = error!.takeUnretainedValue() as AnyObject as! NSError
NSException(name: NSExceptionName.internalInconsistencyException, reason: errorDescription as String, userInfo: [NSUnderlyingErrorKey: nsError]).raise()
}
}
}
| mit | a90988a957446be91e3acbaa641cd959 | 33.175 | 164 | 0.609949 | 4.298742 | false | false | false | false |
MadeByHecho/Timber | Timber/Logger.swift | 1 | 1265 | //
// Logger.swift
// Timber
//
// Created by Scott Petit on 9/7/14.
// Copyright (c) 2014 Scott Petit. All rights reserved.
//
import Foundation
public protocol LoggerType {
var messageFormatter: MessageFormatterType { get }
func logMessage(message: LogMessage)
}
public enum LogLevel: Int, Comparable {
case None = 0
case Error
case Warn
case Info
case Debug
case Verbose
func toString() -> String {
switch self {
case .None:
return "None"
case .Error:
return "ERROR"
case .Warn:
return "WARNING"
case .Info:
return "INFO"
case .Debug:
return "DEBUG"
case .Verbose:
return "VERBOSE"
}
}
}
public func ==(lhs: LogLevel, rhs: LogLevel) -> Bool {
return lhs.rawValue == rhs.rawValue
}
public func <=(lhs: LogLevel, rhs: LogLevel) -> Bool {
return lhs.rawValue <= rhs.rawValue
}
public func >=(lhs: LogLevel, rhs: LogLevel) -> Bool {
return lhs.rawValue >= rhs.rawValue
}
public func >(lhs: LogLevel, rhs: LogLevel) -> Bool {
return lhs.rawValue > rhs.rawValue
}
public func <(lhs: LogLevel, rhs: LogLevel) -> Bool {
return lhs.rawValue < rhs.rawValue
}
| mit | 6c58615cce1b28601bf6e8afa867dee5 | 20.083333 | 56 | 0.592885 | 3.94081 | false | false | false | false |
jopamer/swift | tools/SwiftSyntax/SwiftSyntax.swift | 1 | 4104 | //===--------------- SwiftLanguage.swift - Swift Syntax Library -----------===//
//
// 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
//
//===----------------------------------------------------------------------===//
// This file provides main entry point into the Syntax library.
//===----------------------------------------------------------------------===//
import Foundation
#if os(macOS)
import Darwin
#elseif os(Linux)
import Glibc
#endif
/// A list of possible errors that could be encountered while parsing a
/// Syntax tree.
public enum ParserError: Error, CustomStringConvertible {
case swiftcFailed(Int, String)
case invalidFile
public var description: String {
switch self{
case let .swiftcFailed(exitCode, stderr):
let stderrLines = stderr.split(separator: "\n")
return """
swiftc returned with non-zero exit code \(exitCode)
stderr:
\(stderrLines.joined(separator: "\n "))
"""
case .invalidFile:
return "swiftc created an invalid syntax file"
}
}
}
/// Deserializes the syntax tree from its serialized form to an object tree in
/// Swift. To deserialize incrementally transferred syntax trees, the same
/// instance of the deserializer must be used for all subsequent
/// deserializations.
public final class SyntaxTreeDeserializer {
// FIXME: This lookup table just accumulates nodes, we should invalidate nodes
// that are no longer used at some point and remove them from the table
/// Syntax nodes that have already been parsed and are able to be reused if
/// they were omitted in an incremental syntax tree transfer
private var nodeLookupTable: [SyntaxNodeId: RawSyntax] = [:]
/// The IDs of the nodes that were reused as part of incremental syntax
/// parsing during the last deserialization
public var reusedNodeIds: Set<SyntaxNodeId> = []
public init() {
}
/// Decode a serialized form of SourceFileSyntax to a syntax tree.
/// - Parameter data: The UTF-8 represenation of the serialized syntax tree
/// - Returns: A top-level Syntax node representing the contents of the tree,
/// if the parse was successful.
public func deserialize(_ data: Data) throws -> SourceFileSyntax {
reusedNodeIds = []
let decoder = JSONDecoder()
decoder.userInfo[.rawSyntaxDecodedCallback] = self.addToLookupTable
decoder.userInfo[.omittedNodeLookupFunction] = self.lookupNode
let raw = try decoder.decode(RawSyntax.self, from: data)
guard let file = makeSyntax(raw) as? SourceFileSyntax else {
throw ParserError.invalidFile
}
return file
}
// MARK: Incremental deserialization helper functions
private func lookupNode(id: SyntaxNodeId) -> RawSyntax? {
reusedNodeIds.insert(id)
return nodeLookupTable[id]
}
private func addToLookupTable(_ node: RawSyntax) {
nodeLookupTable[node.id] = node
}
}
/// Namespace for functions to retrieve a syntax tree from the swift compiler
/// and deserializing it.
public enum SyntaxTreeParser {
/// Parses the Swift file at the provided URL into a full-fidelity Syntax tree
/// - Parameter url: The URL you wish to parse.
/// - Returns: A top-level Syntax node representing the contents of the tree,
/// if the parse was successful.
/// - Throws: `ParseError.couldNotFindSwiftc` if `swiftc` could not be
/// located, `ParseError.invalidFile` if the file is invalid.
/// FIXME: Fill this out with all error cases.
public static func parse(_ url: URL) throws -> SourceFileSyntax {
let swiftcRunner = try SwiftcRunner(sourceFile: url)
let result = try swiftcRunner.invoke()
let syntaxTreeData = result.stdoutData
let deserializer = SyntaxTreeDeserializer()
return try deserializer.deserialize(syntaxTreeData)
}
}
| apache-2.0 | bd3c3a54f1a5dd8b57aba29954b2dae7 | 36.651376 | 80 | 0.683967 | 4.642534 | false | false | false | false |
tominated/Quake3BSPParser | Sources/BSPTypes.swift | 1 | 4211 | //
// BSPTypes.swift
// Quake3BSPParser
//
// Created by Thomas Brunoli on 28/05/2017.
// Copyright © 2017 Quake3BSPParser. All rights reserved.
//
import Foundation
import simd
public struct Quake3BSP {
public var entities: BSPEntities?;
public var textures: Array<BSPTexture> = [];
public var planes: Array<BSPPlane> = [];
public var nodes: Array<BSPNode> = [];
public var leaves: Array<BSPLeaf> = [];
public var leafFaces: Array<BSPLeafFace> = [];
public var leafBrushes: Array<BSPLeafBrush> = [];
public var models: Array<BSPModel> = [];
public var brushes: Array<BSPBrush> = [];
public var brushSides: Array<BSPBrushSide> = [];
public var vertices: Array<BSPVertex> = [];
public var meshVerts: Array<BSPMeshVert> = [];
public var effects: Array<BSPEffect> = [];
public var faces: Array<BSPFace> = [];
public var lightmaps: Array<BSPLightmap> = [];
public var lightVols: Array<BSPLightVol> = [];
public var visdata: BSPVisdata?;
init() {}
}
public struct BSPEntities {
public let entities: String;
}
public struct BSPTexture {
public let name: String;
public let surfaceFlags: Int32;
public let contentFlags: Int32;
}
public struct BSPPlane {
public let normal: float3;
public let distance: Float32;
}
public struct BSPNode {
public enum NodeChild {
case node(Int);
case leaf(Int);
}
public let planeIndex: Int32;
public let leftChild: NodeChild;
public let rightChild: NodeChild;
public let boundingBoxMin: int3;
public let boundingBoxMax: int3;
}
public struct BSPLeaf {
public let cluster: Int32;
public let area: Int32;
public let boundingBoxMin: int3;
public let boundingBoxMax: int3;
public let leafFaceIndices: CountableRange<Int32>;
public let leafBrushIndices: CountableRange<Int32>;
}
public struct BSPLeafFace {
public let faceIndex: Int32;
}
public struct BSPLeafBrush {
public let brushIndex: Int32;
}
public struct BSPModel {
public let boundingBoxMin: float3;
public let boundingBoxMax: float3;
public let faceIndices: CountableRange<Int32>;
public let brushIndices: CountableRange<Int32>;
}
public struct BSPBrush {
public let brushSideIndices: CountableRange<Int32>;
public let textureIndex: Int32;
}
public struct BSPBrushSide {
public let planeIndex: Int32;
public let textureIndex: Int32;
}
public struct BSPVertex {
public let position: float3;
public let surfaceTextureCoord: float2;
public let lightmapTextureCoord: float2;
public let normal: float3;
public let color: float4;
public init(
position: float3,
surfaceTextureCoord: float2,
lightmapTextureCoord: float2,
normal: float3,
color: float4
) {
self.position = position
self.surfaceTextureCoord = surfaceTextureCoord
self.lightmapTextureCoord = lightmapTextureCoord
self.normal = normal
self.color = color
}
}
public struct BSPMeshVert {
public let vertexIndexOffset: Int32;
}
public struct BSPEffect {
public let name: String;
public let brushIndex: Int32;
}
public struct BSPFace {
public enum FaceType: Int32 {
case polygon = 1, patch, mesh, billboard;
}
public let textureIndex: Int32;
public let effectIndex: Int32?;
public let type: FaceType;
public let vertexIndices: CountableRange<Int32>;
public let meshVertIndices: CountableRange<Int32>;
public let lightmapIndex: Int32;
public let lightmapStart: int2;
public let lightmapSize: int2;
public let lightmapOrigin: float3;
public let lightmapSVector: float3;
public let lightmapTVector: float3;
public let normal: float3;
public let size: int2;
}
public struct BSPLightmap {
public let lightmap: Array<(UInt8, UInt8, UInt8)>;
}
public struct BSPLightVol {
public let ambientColor: (UInt8, UInt8, UInt8);
public let directionalColor: (UInt8, UInt8, UInt8);
public let direction: (UInt8, UInt8);
}
public struct BSPVisdata {
public let numVectors: Int32;
public let vectorSize: Int32;
public let vectors: Array<UInt8>;
}
| mit | 030ee892adb70beaf3f9bc0ebdd6610b | 25.149068 | 58 | 0.690974 | 3.830755 | false | false | false | false |
blockchain/My-Wallet-V3-iOS | Modules/DelegatedSelfCustody/Sources/DelegatedSelfCustodyDomain/DelegatedCustodyTransactionServiceAPI.swift | 1 | 2030 | // Copyright © Blockchain Luxembourg S.A. All rights reserved.
import Combine
import Errors
import Foundation
import MoneyKit
import ToolKit
public protocol DelegatedCustodyTransactionServiceAPI {
func buildTransaction(
_ transaction: DelegatedCustodyTransactionInput
) -> AnyPublisher<DelegatedCustodyTransactionOutput, DelegatedCustodyTransactionServiceError>
func sign(
_ transaction: DelegatedCustodyTransactionOutput,
privateKey: Data
) -> Result<DelegatedCustodySignedTransactionOutput, DelegatedCustodyTransactionServiceError>
func pushTransaction(
_ transaction: DelegatedCustodySignedTransactionOutput,
currency: CryptoCurrency
) -> AnyPublisher<String, DelegatedCustodyTransactionServiceError>
}
public enum DelegatedCustodyTransactionServiceError: Error {
case authenticationError(AuthenticationDataRepositoryError)
case networkError(NetworkError)
case signing(DelegatedCustodySigningError)
}
public enum AuthenticationDataRepositoryError: Error {
case missingGUID
case missingSharedKey
}
public struct DelegatedCustodySignedTransactionOutput {
public struct SignedPreImage {
public let preImage: String
public let signingKey: String
public let signatureAlgorithm: DelegatedCustodySignatureAlgorithm
public let signature: String
public init(
preImage: String,
signingKey: String,
signatureAlgorithm: DelegatedCustodySignatureAlgorithm,
signature: String
) {
self.preImage = preImage
self.signingKey = signingKey
self.signatureAlgorithm = signatureAlgorithm
self.signature = signature
}
}
public let rawTx: JSONValue
public let signatures: [SignedPreImage]
public init(
rawTx: JSONValue,
signatures: [DelegatedCustodySignedTransactionOutput.SignedPreImage]
) {
self.rawTx = rawTx
self.signatures = signatures
}
}
| lgpl-3.0 | 42bbbf30253dfd6482e0b243851a3d6e | 29.742424 | 97 | 0.727452 | 5.353562 | false | false | false | false |
huonw/swift | stdlib/public/SDK/SafariServices/SafariServices.swift | 18 | 860 | //===----------------------------------------------------------------------===//
//
// 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
//
//===----------------------------------------------------------------------===//
@_exported import SafariServices // Clang module
import _SwiftSafariServicesOverlayShims
#if os(macOS)
@available(macOS, introduced: 10.11)
public func SFSafariServicesAvailable(_ version: SFSafariServicesVersion = SFSafariServicesVersion.version10_0) -> Bool {
return _swift_SafariServices_isSafariServicesAvailable(version)
}
#endif
| apache-2.0 | f60b67fc7aa98788d4e243ba0a0d29f9 | 36.391304 | 121 | 0.631395 | 4.914286 | false | false | false | false |
yeokm1/nus-soc-print-ios | NUS SOC Print/PrintingViewTableCell.swift | 1 | 976 | //
// PrintingViewTableCell.swift
// NUS SOC Print
//
// Created by Yeo Kheng Meng on 17/8/14.
// Copyright (c) 2014 Yeo Kheng Meng. All rights reserved.
//
import Foundation
import UIKit
class PrintingViewTableCell : UITableViewCell {
@IBOutlet weak var header: UILabel!
@IBOutlet weak var smallFooter: UILabel!
@IBOutlet weak var progressBar: UIProgressView!
@IBOutlet weak var tick: UIImageView!
@IBOutlet weak var activityIndicator: UIActivityIndicatorView!
@IBOutlet weak var cross: UIImageView!
override func prepareForReuse() {
super.prepareForReuse()
header.text = ""
smallFooter.text = ""
progressBar.hidden = true
progressBar.setProgress(0, animated: false)
tick.hidden = true
cross.hidden = true
if(activityIndicator.isAnimating()){
activityIndicator.stopAnimating()
}
activityIndicator.hidden = true
}
}
| mit | 561ef0ddcff1cb8d1c893aa6bc4732db | 24.684211 | 66 | 0.653689 | 4.737864 | false | false | false | false |
ytfhqqu/iCC98 | iCC98/iCC98/BoardTableViewController.swift | 1 | 5597 | //
// BoardTableViewController.swift
// iCC98
//
// Created by Duo Xu on 5/4/17.
// Copyright © 2017 Duo Xu.
//
// 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 SVProgressHUD
import CC98Kit
class BoardTableViewController: BaseTableViewController {
// MARK: - Data
/**
设置数据。
- parameter parentBoardId: 父版面的标识。
*/
func setData(parentBoardId: Int) {
shouldGetRootBoards = false
fetchData(parentBoardId: parentBoardId)
}
/// 表示是否要获取根版面的信息。如果为真,在 `viewDidLoad()` 时自动加载根版面的信息;如果为假,则在使用 `setData(parentBoardId:)` 指定版面后,获取其子版面的信息。
private var shouldGetRootBoards = true
/// 版面的信息。
private var boards = [BoardInfo]() {
didSet {
tableView.reloadData()
}
}
/// 表示是否有数据。
override var hasData: Bool {
return !boards.isEmpty
}
/// 获取根版面的数据。
private func fetchData() {
isLoading = true
_ = CC98API.getRootBoards { [weak self] result in
switch result {
case .success(_, let data):
if let boardInfoArray = data {
self?.boards = boardInfoArray
}
case .failure(let status, let message):
SVProgressHUD.showError(statusCode: status, message: message)
case .noResponse:
SVProgressHUD.showNoResponseError()
}
self?.isLoading = false
}
}
/// 根据父版面获取子版面的数据。
private func fetchData(parentBoardId: Int) {
isLoading = true
_ = CC98API.getSubBoards(ofBoard: parentBoardId, accessToken: OAuthUtility.accessToken) { [weak self] result in
switch result {
case .success(_, let data):
if let boardInfoArray = data {
self?.boards = boardInfoArray
}
case .failure(let status, let message):
SVProgressHUD.showError(statusCode: status, message: message)
case .noResponse:
SVProgressHUD.showNoResponseError()
}
self?.isLoading = false
}
}
// MARK: - View controller lifecycle
override func viewDidLoad() {
super.viewDidLoad()
// 获取根版面的数据
if shouldGetRootBoards {
fetchData()
}
}
// MARK: - Table view data source
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return boards.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let boardInfo = boards[indexPath.row]
let identifier: String
// if let childCount = boardInfo.childCount, childCount > 0 {
// identifier = "Non-leaf Board Cell"
// } else {
identifier = "Leaf Board Cell"
// }
let cell = tableView.dequeueReusableCell(withIdentifier: identifier, for: indexPath)
// Configure the cell...
if let boardCell = cell as? BoardTableViewCell {
boardCell.setData(boardInfo: boardInfo)
}
return cell
}
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
if let cell = sender as? UITableViewCell, let indexPath = tableView.indexPath(for: cell) {
let boardInfo = boards[indexPath.row]
if segue.identifier == "Subboards", let boardTVC = segue.destination as? BoardTableViewController {
boardTVC.setData(parentBoardId: boardInfo.id ?? 0)
boardTVC.navigationItem.title = boardInfo.name
} else if segue.identifier == "Topics", let topicTVC = segue.destination as? TopicTableViewController {
topicTVC.setData(boardId: boardInfo.id ?? 0)
topicTVC.navigationItem.title = boardInfo.name
}
}
}
}
| mit | 7f6ba28a4058a320ee5cbf46dd0a6ad1 | 35.026846 | 119 | 0.625 | 4.599829 | false | false | false | false |
Alloc-Studio/Hypnos | Hypnos/Hypnos/ViewModel/Controller/Main/LeftViewController.swift | 2 | 3220 | //
// LeftViewController.swift
// Hypnos
//
// Created by Fay on 16/5/18.
// Copyright © 2016年 DMT312. All rights reserved.
//
import UIKit
class LeftViewController: UITableViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Uncomment the following line to preserve selection between presentations
// self.clearsSelectionOnViewWillAppear = false
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return 10
}
/*
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("reuseIdentifier", forIndexPath: indexPath)
// Configure the cell...
return cell
}
*/
/*
// Override to support conditional editing of the table view.
override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return false if you do not want the specified item to be editable.
return true
}
*/
/*
// Override to support editing the table view.
override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if editingStyle == .Delete {
// Delete the row from the data source
tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
} else if editingStyle == .Insert {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
}
}
*/
/*
// Override to support rearranging the table view.
override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) {
}
*/
/*
// Override to support conditional rearranging of the table view.
override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return false if you do not want the item to be re-orderable.
return true
}
*/
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| mit | b1c998fc5026ed3771d0c7adcb6d2039 | 32.863158 | 157 | 0.685732 | 5.556131 | false | false | false | false |
cuappdev/eatery | Shared/Models/Eatery.swift | 1 | 8278 | //
// Eatery.swift
// Eatery
//
// Created by William Ma on 3/9/19.
// Copyright © 2019 CUAppDev. All rights reserved.
//
import CoreLocation
import UIKit
// MARK: - Eatery Data
/// Different meals served by eateries
enum Meal: String {
case breakfast = "Breakfast"
case brunch = "Brunch"
case liteLunch = "Lite Lunch"
case lunch = "Lunch"
case dinner = "Dinner"
}
/// Assorted types of payment accepted by an Eatery
enum PaymentMethod: String {
case brb = "Meal Plan - Debit"
case swipes = "Meal Plan - Swipe"
case cash = "Cash"
case cornellCard = "Cornell Card"
case creditCard = "Major Credit Cards"
case nfc = "Mobile Payments"
case other = "Other"
}
/// Different types of eateries on campus
enum EateryType: String {
case dining = "all you care to eat dining room"
case cafe = "cafe"
case cart = "cart"
case foodCourt = "food court"
case convenienceStore = "convenience store"
case coffeeShop = "coffee shop"
case bakery = "bakery"
case unknown = ""
}
enum EateryStatus {
static func equalsIgnoreAssociatedValue(_ lhs: EateryStatus, rhs: EateryStatus) -> Bool {
switch (lhs, rhs) {
case (.openingSoon, .openingSoon),
(.open, .open),
(.closingSoon, .closingSoon),
(.closed, .closed): return true
default: return false
}
}
case openingSoon(minutesUntilOpen: Int)
case open
case closingSoon(minutesUntilClose: Int)
case closed
}
// MARK: - Eatery
protocol Eatery {
/// A string of the form YYYY-MM-dd (ISO 8601 Calendar dates)
/// Read more: https://en.wikipedia.org/wiki/ISO_8601#Calendar_dates
typealias DayString = String
typealias EventName = String
var id: Int { get }
var name: String { get }
var displayName: String { get }
var imageUrl: URL? { get }
var eateryType: EateryType { get }
var address: String { get }
var paymentMethods: [PaymentMethod] { get }
var location: CLLocation { get }
var phone: String { get }
var events: [DayString: [EventName: Event]] { get }
var allEvents: [Event] { get }
}
/// Converts the date to its day for use with eatery events
private let dayFormatter: ISO8601DateFormatter = {
let formatter = ISO8601DateFormatter()
formatter.formatOptions = [.withFullDate, .withDashSeparatorInDate]
formatter.timeZone = TimeZone(identifier: "America/New_York")
return formatter
}()
// MARK: - Utils
extension Eatery {
/// The event at an exact date and time, or nil if such an event does not
/// exist.
func event(atExactly date: Date) -> Event? {
return allEvents.first { $0.dateInterval.contains(date) }
}
/// The events that happen within the specified time interval, regardless of
/// the day the event occurs on
/// i.e. events that are active for any amount of time during the interval.
func events(in dateInterval: DateInterval) -> [Event] {
return allEvents.filter { dateInterval.intersects($0.dateInterval) }
}
/// The events by name that occur on the specified day
// Since events may extend past midnight, this function is required to pick
// a specific day for an event.
func eventsByName(onDayOf date: Date) -> [EventName: Event] {
let dayString = dayFormatter.string(from: date)
return events[dayString] ?? [:]
}
func isOpen(onDayOf date: Date) -> Bool {
return !eventsByName(onDayOf: date).isEmpty
}
func isOpenToday() -> Bool {
return isOpen(onDayOf: Date())
}
func isOpen(atExactly date: Date) -> Bool {
return event(atExactly: date) != nil
}
func activeEvent(atExactly date: Date) -> Event? {
let calendar = Calendar.current
guard let yesterday = calendar.date(byAdding: .day, value: -1, to: date),
let tomorrow = calendar.date(byAdding: .day, value: 1, to: date) else {
return nil
}
return events(in: DateInterval(start: yesterday, end: tomorrow))
.filter {
// disregard events that are not currently happening or that have happened in the past
$0.occurs(atExactly: date) || date < $0.start
}.min { (lhs, rhs) -> Bool in
if lhs.occurs(atExactly: date) {
return true
} else if rhs.occurs(atExactly: date) {
return false
}
let timeUntilLeftStart = lhs.start.timeIntervalSince(date)
let timeUntilRightStart = rhs.start.timeIntervalSince(date)
return timeUntilLeftStart < timeUntilRightStart
}
}
func currentActiveEvent() -> Event? {
return activeEvent(atExactly: Date())
}
func status(onDayOf date: Date) -> EateryStatus {
guard isOpen(onDayOf: date) else {
return .closed
}
guard let event = activeEvent(atExactly: date) else {
return .closed
}
switch event.status(atExactly: date) {
case .notStarted:
return .closed
case .startingSoon:
let minutesUntilOpen = Int(event.start.timeIntervalSinceNow / 60) + 1
return .openingSoon(minutesUntilOpen: minutesUntilOpen)
case .started:
return .open
case .endingSoon:
let minutesUntilClose = Int(event.end.timeIntervalSinceNow / 60) + 1
return .closingSoon(minutesUntilClose: minutesUntilClose)
case .ended:
return .closed
}
}
func currentStatus() -> EateryStatus {
return status(onDayOf: Date())
}
}
// MARK: - User Defaults / Favoriting
extension Eatery {
func isFavorite() -> Bool {
return UserDefaults.standard.stringArray(forKey: "favorites")?.contains(name) ?? false
}
func setFavorite(_ newValue: Bool) {
var ar = UserDefaults.standard.stringArray(forKey: "favorites") ?? []
if newValue {
ar.append(name)
} else {
ar.removeAll(where: { $0 == name })
}
UserDefaults.standard.set(ar, forKey: "favorites")
NotificationCenter.default.post(name: .eateryIsFavoriteDidChange, object: self)
}
}
extension NSNotification.Name {
static let eateryIsFavoriteDidChange = NSNotification.Name("org.cuappdev.eatery.eateryIsFavoriteDidChangeNotificationName")
}
// MARK: - Presentation
struct EateryPresentation {
let statusText: String
let statusColor: UIColor
let nextEventText: String
}
private let timeFormatter: DateFormatter = {
let formatter = DateFormatter()
formatter.dateStyle = .none
formatter.timeStyle = .short
return formatter
}()
extension Eatery {
func currentPresentation() -> EateryPresentation {
let statusText: String
let statusColor: UIColor
let nextEventText: String
switch currentStatus() {
case let .openingSoon(minutesUntilOpen):
statusText = "Opening"
statusColor = .eateryOrange
nextEventText = "in \(minutesUntilOpen)m"
case .open:
statusText = "Open"
statusColor = .eateryGreen
if let currentEvent = currentActiveEvent() {
let endTimeText = timeFormatter.string(from: currentEvent.end)
nextEventText = "until \(endTimeText)"
} else {
nextEventText = ""
}
case let .closingSoon(minutesUntilClose):
statusText = "Closing"
statusColor = .eateryOrange
nextEventText = "in \(minutesUntilClose)m"
case .closed:
statusText = "Closed"
statusColor = .eateryRed
if isOpenToday(), let nextEvent = currentActiveEvent() {
let startTimeText = timeFormatter.string(from: nextEvent.start)
nextEventText = "until \(startTimeText)"
} else {
nextEventText = "today"
}
}
return EateryPresentation(statusText: statusText,
statusColor: statusColor,
nextEventText: nextEventText)
}
}
| mit | fe0797f17d47e90d4310e186ffa77aaa | 26.226974 | 127 | 0.613024 | 4.379365 | false | false | false | false |
binarylevel/Tinylog-iOS | Tinylog/View Controllers/iPad/TLISplitViewController.swift | 1 | 1590 | //
// TLISplitViewController.swift
// Tinylog
//
// Created by Spiros Gerokostas on 18/10/15.
// Copyright © 2015 Spiros Gerokostas. All rights reserved.
//
import UIKit
class TLISplitViewController: UISplitViewController, UISplitViewControllerDelegate {
var listsViewController:TLIListsViewController?
var listViewController:TLITasksViewController?
override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) {
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
listsViewController = TLIListsViewController()
listViewController = TLITasksViewController()
let navigationController1:UINavigationController = UINavigationController(rootViewController: listsViewController!)
let navigationController2:UINavigationController = UINavigationController(rootViewController: listViewController!)
self.viewControllers = [navigationController1, navigationController2]
self.delegate = self
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
class func sharedSplitViewController()->TLISplitViewController {
return TLIAppDelegate.sharedAppDelegate().window?.rootViewController as! TLISplitViewController
}
override func viewDidLoad() {
super.viewDidLoad()
}
func splitViewController(svc: UISplitViewController, shouldHideViewController vc: UIViewController, inOrientation orientation: UIInterfaceOrientation) -> Bool {
return false
}
}
| mit | 3d7ad6a4003fba6c4638cb08c95cbf87 | 35.113636 | 164 | 0.736312 | 6.088123 | false | false | false | false |
Turistforeningen/SjekkUT | ios/SjekkUt/model/ProjectExtension.swift | 1 | 1537 | //
// ProjectExtension.swift
// SjekkUt
//
// Created by Henrik Hartz on 20/04/2017.
// Copyright © 2017 Den Norske Turistforening. All rights reserved.
//
import Foundation
extension Project {
class func fetchedResults() -> NSFetchedResultsController<Project> {
let fetchRequest = Project.fetchRequest()
let context = ModelController.instance.managedObjectContext!
let results = NSFetchedResultsController.init(fetchRequest: fetchRequest, managedObjectContext: context, sectionNameKeyPath: nil, cacheName: nil)
do {
try results.performFetch()
} catch(let error) {
DntManager.logError(error)
}
return results
}
class var validProjectsPredicate:NSPredicate {
get {
let dateSpan = Project.validDateRange()
let predicate = NSPredicate(format: "name != NULL AND isHidden = NO AND (start == NULL || start <= %@) AND (stop == NULL || stop >= %@)", argumentArray: [dateSpan.stop, dateSpan.start])
return predicate
}
}
class var allProjectsPredicate:NSPredicate {
get {
let predicate = NSPredicate(format: "name != NULL")
return predicate
}
}
var isExpired: Bool {
get {
let expired = (stop?.timeIntervalSinceNow ?? Double.greatestFiniteMagnitude) < -TimeInterval(7 * 24 * 60 * 60)
return expired
}
}
static let placeholderImage = UIImage(named: "project-fallback")!
}
| mit | ff79e5c793f3ffb93a539aae1f4eb7af | 31 | 197 | 0.621094 | 5.003257 | false | false | false | false |
robbdimitrov/pixelgram-ios | PixelGram/Classes/Screens/Feed/UsersViewController.swift | 1 | 5067 | //
// UsersViewController.swift
// PixelGram
//
// Created by Robert Dimitrov on 11/21/17.
// Copyright © 2017 Robert Dimitrov. All rights reserved.
//
import UIKit
class UsersViewController: CollectionViewController {
var viewModel: UsersViewModel?
private var dataSource: CollectionViewDataSource?
private var page: Int = 0
// MARK: - View Lifecycle
override func viewDidLoad() {
super.viewDidLoad()
setupRefreshControl()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
loadUsers(for: page) { [weak self] in
self?.collectionView?.reloadData()
}
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
if let collectionView = collectionView, let flowLayout = collectionView.collectionViewLayout as? UICollectionViewFlowLayout {
flowLayout.estimatedItemSize = CGSize(width: collectionView.frame.width, height: 70)
}
}
// MARK: - Data
override func handleRefresh(_ sender: UIRefreshControl) {
page = 0
viewModel?.users.removeAll()
loadUsers(for: page) { [weak self] in
self?.collectionView?.reloadData()
if self?.collectionView?.refreshControl?.isRefreshing ?? false {
self?.collectionView?.refreshControl?.endRefreshing()
}
}
}
func loadUsers(for page: Int, limit: Int = 20, completionBlock: (() -> Void)?) {
guard let imageId = viewModel?.imageId else {
return
}
APIClient.shared.loadUsersLikedImage(withId: imageId, page: page, limit: limit, completion: { [weak self] users in
self?.page = page
self?.viewModel?.users.append(contentsOf: users)
completionBlock?()
}) { [weak self] error in
self?.showError(error: error)
}
}
// MARK: - Helpers
func loadNextPage() {
let oldCount = viewModel?.users.count ?? 0
loadUsers(for: page + 1) { [weak self] in
let count = self?.viewModel?.users.count ?? 0
guard count > oldCount else {
return
}
var indexPaths = [IndexPath]()
for index in oldCount...(count - 1) {
let indexPath = IndexPath(row: index, section: 0)
indexPaths.append(indexPath)
}
self?.collectionView?.insertItems(at: indexPaths)
}
}
// MARK: - Components
func createDataSource() -> CollectionViewDataSource {
let dataSource = CollectionViewDataSource(configureCell: { [weak self] (collectionView, indexPath) -> UICollectionViewCell in
if indexPath.row == (self?.viewModel?.users.count ?? 0) - 1 {
self?.loadNextPage()
}
return (self?.configureCell(collectionView: collectionView, indexPath: indexPath))!
}, numberOfItems: { [weak self] (collectionView, section) -> Int in
return self?.viewModel?.numberOfItems ?? 0
})
return dataSource
}
// MARK: - Cells
func configureCell(collectionView: UICollectionView, indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: UserCell.reuseIdentifier, for: indexPath)
if let cell = cell as? UserCell, let userViewModel = viewModel?.userViewModel(forIndex: indexPath.row) {
cell.configure(with: userViewModel)
}
return cell
}
// MARK: - Reactive
func handleCellSelection(collectionView: UICollectionView?) {
collectionView?.rx.itemSelected.bind { [weak self] indexPath in
self?.openUserProfile(atIndex: indexPath.item)
}.disposed(by: disposeBag)
}
// MARK: - Navigation
private func openUserProfile(atIndex index: Int) {
if let userId = viewModel?.users[index].id {
openUserProfile(withUserId: userId)
}
}
private func openUserProfile(withUserId userId: String) {
let viewController = instantiateViewController(withIdentifier:
ProfileViewController.storyboardIdentifier)
(viewController as? ProfileViewController)?.userId = userId
navigationController?.pushViewController(viewController, animated: true)
}
// MARK: - Config
func setupRefreshControl() {
collectionView?.alwaysBounceVertical = true
collectionView?.refreshControl = refreshControl
}
override func setupNavigationItem() {
super.setupNavigationItem()
title = "Likes"
}
override func configureCollectionView() {
dataSource = createDataSource()
collectionView?.dataSource = dataSource
handleCellSelection(collectionView: collectionView)
}
}
| mit | 16251c6abf4bbd3b818be003c78217f5 | 31.474359 | 133 | 0.604224 | 5.54874 | false | false | false | false |
richardpiazza/LCARSDisplayKit | Sources/LCARSDisplayKit/Arc.swift | 1 | 2971 | #if (os(macOS) || os(iOS) || os(tvOS) || os(watchOS))
import CoreGraphics
import GraphPoint
/// Arc of a circle (a continuous length around the circumference)
public struct Arc: Graphable {
public var size: CGSize = CGSize.zero
public var radius: CGFloat = CGFloat(0)
public var startDegree: CGFloat = CGFloat(0)
public var endDegree: CGFloat = CGFloat(0)
/// A `GraphPoint` used to verticaly/horizontaly clip the starting degree
public var boundedStart: GraphPoint?
/// A `GraphPoint` used to verticaly/horizontaly clip the ending degree
public var boundedEnd: GraphPoint?
public init() {
}
public init(radius: CGFloat, startDegree: CGFloat, endDegree: CGFloat) {
self.radius = radius
self.startDegree = startDegree
self.endDegree = endDegree
}
/// The `GraphPoint` corresponding to the startDegree and radius
public var startPoint: GraphPoint {
if let boundedStart = self.boundedStart {
return GraphPoint.graphPoint(degree: startDegree, radius: radius, boundedBy: boundedStart)
}
return GraphPoint.graphPoint(degree: startDegree, radius: radius)
}
/// The `GraphPoint` corresponding to the endDegree and radius
public var endPoint: GraphPoint {
if let boundedEnd = self.boundedEnd {
return GraphPoint.graphPoint(degree: endDegree, radius: radius, boundedBy: boundedEnd)
}
return GraphPoint.graphPoint(degree: endDegree, radius: radius)
}
/// Calculates the point of the right angle that joins the start and end points.
public var pivot: GraphPoint {
let start = startPoint
let end = endPoint
var pivot = GraphPoint(x: 0, y: 0)
if startDegree < 90 {
pivot.x = end.x
pivot.y = start.y
} else if startDegree < 180 {
pivot.x = start.x
pivot.y = end.y
} else if startDegree < 270 {
pivot.x = end.x
pivot.y = start.y
} else {
pivot.x = start.x
pivot.y = end.y
}
return pivot
}
// MARK: - Graphable
public var graphPoints: [GraphPoint] {
return [startPoint, endPoint]
}
public var graphFrame: GraphFrame {
return GraphFrame.graphFrame(graphPoints: graphPoints, radius: radius, startDegree: startDegree, endDegree: endDegree)
}
public var path: CGMutablePath {
let path: CGMutablePath = CGMutablePath()
let gf = graphFrame
let offset = gf.graphOriginOffset
let translatedPivot = gf.boundedPoint(graphPoint: pivot)
path.addArc(center: offset, radius: radius, startAngle: startDegree.radians, endAngle: endDegree.radians, clockwise: false)
path.addLine(to: translatedPivot)
path.closeSubpath()
return path
}
}
#endif
| mit | 5ae0a21c6e3a3fc42b660d70fa41f8a9 | 31.648352 | 131 | 0.62134 | 4.591963 | false | false | false | false |
kevinmbeaulieu/Signal-iOS | Signal/src/UserInterface/Strings.swift | 2 | 1011 | //
// Copyright (c) 2017 Open Whisper Systems. All rights reserved.
//
import Foundation
/**
* Strings re-used in multiple places should be added here.
*/
@objc class CallStrings: NSObject {
static let callBackButtonTitle = NSLocalizedString("CALLBACK_BUTTON_TITLE", comment: "notification action")
static let missedCallNotificationBody = NSLocalizedString("MISSED_CALL", comment: "notification title")
static let missedCallNotificationBodyWithCallerName = NSLocalizedString("MSGVIEW_MISSED_CALL_WITH_NAME", comment: "notification title. Embeds {{Caller's Name}}")
static let missedCallNotificationBodyWithoutCallerName = NSLocalizedString("MSGVIEW_MISSED_CALL_WITHOUT_NAME", comment: "notification title.")
static let callStatusFormat = NSLocalizedString("CALL_STATUS_FORMAT", comment: "embeds {{Call Status}} in call screen label. For ongoing calls, {{Call Status}} is a seconds timer like 01:23, otherwise {{Call Status}} is a short text like 'Ringing', 'Busy', or 'Failed Call'")
}
| gpl-3.0 | 08d5c4c8e9a4a8c5d7cb0cf4fb9344d7 | 62.1875 | 279 | 0.762611 | 4.453744 | false | false | false | false |
dangnguyenhuu/JSQMessagesSwift | Sources/Categories/JSQSystemSoundPlayer+Messages.swift | 1 | 2094 | //
// JSQSystemSoundPlayer.swift
// JSQMessagesViewController
//
// Created by Sylvain FAY-CHATELARD on 19/08/2015.
// Copyright (c) 2015 Dviance. All rights reserved.
//
//import JSQSystemSoundPlayer_Swift
//
//let kJSQMessageReceivedSoundName = "message_received"
//let kJSQMessageSentSoundName = "message_sent"
//
//extension JSQSystemSoundPlayer {
//
// public class func jsq_playMessageReceivedSound() {
//
// JSQSystemSoundPlayer.jsq_playSoundFromJSQMessagesBundle(name: kJSQMessageReceivedSoundName, asAlert: false)
// }
//
// public class func jsq_playMessageReceivedAlert() {
//
// JSQSystemSoundPlayer.jsq_playSoundFromJSQMessagesBundle(name: kJSQMessageReceivedSoundName, asAlert: true)
// }
//
// public class func jsq_playMessageSentSound() {
//
// JSQSystemSoundPlayer.jsq_playSoundFromJSQMessagesBundle(name: kJSQMessageSentSoundName, asAlert: false)
// }
//
// public class func jsq_playMessageSentAlert() {
//
// JSQSystemSoundPlayer.jsq_playSoundFromJSQMessagesBundle(name: kJSQMessageSentSoundName, asAlert: true)
// }
//
// fileprivate class func jsq_playSoundFromJSQMessagesBundle(name: String, asAlert: Bool) {
//
// // Save sound player original bundle
// let originalPlayerBundleIdentifier = JSQSystemSoundPlayer.sharedPlayer.bundle
//
// if let bundle = Bundle.jsq_messagesBundle() {
//
// JSQSystemSoundPlayer.sharedPlayer.bundle = bundle
// }
//
// let filename = "JSQMessagesAssets.bundle/Sounds/\(name)"
//
// if asAlert {
//
// JSQSystemSoundPlayer.sharedPlayer.playAlertSound(filename, fileExtension: JSQSystemSoundPlayer.TypeAIFF, completion: nil)
// }
// else {
//
// JSQSystemSoundPlayer.sharedPlayer.playSound(filename, fileExtension: JSQSystemSoundPlayer.TypeAIFF, completion: nil)
// }
//
// JSQSystemSoundPlayer.sharedPlayer.bundle = originalPlayerBundleIdentifier
// }
//}
| apache-2.0 | 1a0e438d860fe7d05aa9dcd4b3984f7f | 34.491525 | 135 | 0.666667 | 4.326446 | false | false | false | false |
raymondshadow/SwiftDemo | SwiftApp/Pods/Swiftz/Sources/Swiftz/EitherExt.swift | 3 | 5841 | //
// EitherExt.swift
// Swiftz
//
// Created by Robert Widmann on 6/21/15.
// Copyright © 2015 TypeLift. All rights reserved.
//
#if SWIFT_PACKAGE
import Operadics
import Swiftx
#endif
extension Either /*: Bifunctor*/ {
public typealias B = Any
public typealias D = Any
public typealias PAC = Either<L, R>
public typealias PAD = Either<L, D>
public typealias PBC = Either<B, R>
public typealias PBD = Either<B, D>
public func bimap<B, D>(_ f : (L) -> B, _ g : ((R) -> D)) -> Either<B, D> {
switch self {
case let .Left(bx):
return Either<B, D>.Left(f(bx))
case let .Right(bx):
return Either<B, D>.Right(g(bx))
}
}
public func leftMap<B>(_ f : @escaping (L) -> B) -> Either<B, R> {
return self.bimap(f, identity)
}
public func rightMap(_ g : @escaping (R) -> D) -> Either<L, D> {
return self.bimap(identity, g)
}
}
extension Either /*: Functor*/ {
public typealias FB = Either<L, B>
public func fmap<B>(_ f : (R) -> B) -> Either<L, B> {
return f <^> self
}
}
extension Either /*: Pointed*/ {
public typealias A = R
public static func pure(_ r : R) -> Either<L, R> {
return .Right(r)
}
}
extension Either /*: Applicative*/ {
public typealias FAB = Either<L, (R) -> B>
public func ap<B>(_ f : Either<L, (R) -> B>) -> Either<L, B> {
return f <*> self
}
}
extension Either /*: Cartesian*/ {
public typealias FTOP = Either<L, ()>
public typealias FTAB = Either<L, (A, B)>
public typealias FTABC = Either<L, (A, B, C)>
public typealias FTABCD = Either<L, (A, B, C, D)>
public static var unit : Either<L, ()> { return .Right(()) }
public func product<B>(_ r : Either<L, B>) -> Either<L, (A, B)> {
switch self {
case let .Left(c):
return .Left(c)
case let .Right(d):
switch r {
case let .Left(e):
return .Left(e)
case let .Right(f):
return .Right((d, f))
}
}
}
public func product<B, C>(_ r : Either<L, B>, _ s : Either<L, C>) -> Either<L, (A, B, C)> {
switch self {
case let .Left(c):
return .Left(c)
case let .Right(d):
switch r {
case let .Left(e):
return .Left(e)
case let .Right(f):
switch s {
case let .Left(g):
return .Left(g)
case let .Right(h):
return .Right((d, f, h))
}
}
}
}
public func product<B, C, D>(_ r : Either<L, B>, _ s : Either<L, C>, _ t : Either<L, D>) -> Either<L, (A, B, C, D)> {
switch self {
case let .Left(c):
return .Left(c)
case let .Right(d):
switch r {
case let .Left(e):
return .Left(e)
case let .Right(f):
switch s {
case let .Left(g):
return .Left(g)
case let .Right(h):
switch t {
case let .Left(i):
return .Left(i)
case let .Right(j):
return .Right((d, f, h, j))
}
}
}
}
}
}
extension Either /*: ApplicativeOps*/ {
public typealias C = Any
public typealias FC = Either<L, C>
public typealias FD = Either<L, D>
public static func liftA<B>(_ f : @escaping (A) -> B) -> (Either<L, A>) -> Either<L, B> {
return { (a : Either<L, A>) -> Either<L, B> in Either<L, (A) -> B>.pure(f) <*> a }
}
public static func liftA2<B, C>(_ f : @escaping (A) -> (B) -> C) -> (Either<L, A>) -> (Either<L, B>) -> Either<L, C> {
return { (a : Either<L, A>) -> (Either<L, B>) -> Either<L, C> in { (b : Either<L, B>) -> Either<L, C> in f <^> a <*> b } }
}
public static func liftA3<B, C, D>(_ f : @escaping (A) -> (B) -> (C) -> D) -> (Either<L, A>) -> (Either<L, B>) -> (Either<L, C>) -> Either<L, D> {
return { (a : Either<L, A>) -> (Either<L, B>) -> (Either<L, C>) -> Either<L, D> in { (b : Either<L, B>) -> (Either<L, C>) -> Either<L, D> in { (c : Either<L, C>) -> Either<L, D> in f <^> a <*> b <*> c } } }
}
}
extension Either /*: Monad*/ {
public func bind<B>(_ f : (A) -> Either<L, B>) -> Either<L, B> {
return self >>- f
}
}
extension Either /*: MonadOps*/ {
public static func liftM<B>(_ f : @escaping (A) -> B) -> (Either<L, A>) -> Either<L, B> {
return { (m1 : Either<L, A>) -> Either<L, B> in m1 >>- { (x1 : A) -> Either<L, B> in Either<L, B>.pure(f(x1)) } }
}
public static func liftM2<B, C>(_ f : @escaping (A) -> (B) -> C) -> (Either<L, A>) -> (Either<L, B>) -> Either<L, C> {
return { (m1 : Either<L, A>) -> (Either<L, B>) -> Either<L, C> in { (m2 : Either<L, B>) -> Either<L, C> in m1 >>- { (x1 : A) in m2 >>- { (x2 : B) in Either<L, C>.pure(f(x1)(x2)) } } } }
}
public static func liftM3<B, C, D>(_ f : @escaping (A) -> (B) -> (C) -> D) -> (Either<L, A>) -> (Either<L, B>) -> (Either<L, C>) -> Either<L, D> {
return { (m1 : Either<L, A>) -> (Either<L, B>) -> (Either<L, C>) -> Either<L, D> in { (m2 : Either<L, B>) -> (Either<L, C>) -> Either<L, D> in { (m3 : Either<L, C>) -> Either<L, D> in m1 >>- { (x1 : A) in m2 >>- { (x2 : B) in m3 >>- { (x3 : C) in Either<L, D>.pure(f(x1)(x2)(x3)) } } } } } }
}
}
public func >>->> <L, A, B, C>(_ f : @escaping (A) -> Either<L, B>, g : @escaping (B) -> Either<L, C>) -> ((A) -> Either<L, C>) {
return { x in f(x) >>- g }
}
public func <<-<< <L, A, B, C>(g : @escaping (B) -> Either<L, C>, f : @escaping (A) -> Either<L, B>) -> ((A) -> Either<L, C>) {
return f >>->> g
}
extension Either /*: Foldable*/ {
public func foldr<B>(k : (A) -> (B) -> B, _ i : B) -> B {
switch self {
case .Left(_):
return i
case .Right(let y):
return k(y)(i)
}
}
public func foldl<B>(k : (B) -> (A) -> B, _ i : B) -> B {
switch self {
case .Left(_):
return i
case .Right(let y):
return k(i)(y)
}
}
public func foldMap<M : Monoid>(_ f : (A) -> M) -> M {
switch self {
case .Left(_):
return M.mempty
case .Right(let y):
return f(y)
}
}
}
public func sequence<L, R>(_ ms : [Either<L, R>]) -> Either<L, [R]> {
return ms.reduce(Either<L, [R]>.pure([]), { n, m in
return n.bind { xs in
return m.bind { x in
return Either<L, [R]>.pure(xs + [x])
}
}
})
}
| apache-2.0 | d533d6def76e3e180210fa3574a62a13 | 26.54717 | 293 | 0.521747 | 2.468301 | false | false | false | false |
mathcamp/swiftz | swiftz/Num.swift | 2 | 2576 | //
// Num.swift
// swiftz
//
// Created by Maxwell Swadling on 3/06/2014.
// Copyright (c) 2014 Maxwell Swadling. All rights reserved.
//
// Num 'typeclass'
public protocol Num {
typealias N
func zero() -> N
func succ(n: N) -> N
func add(x: N, y: N) -> N
func multiply(x: N, y: N) -> N
}
public let nint8 = NInt8()
public class NInt8: Num {
public typealias N = Int8
public func zero() -> N { return 0 }
public func succ(n: N) -> N { return n + 1 }
public func add(x: N, y: N) -> N { return x + y }
public func multiply(x: N, y: N) -> N { return x * y }
}
public let nint16 = NInt16()
public class NInt16: Num {
public typealias N = Int16
public func zero() -> N { return 0 }
public func succ(n: N) -> N { return n + 1 }
public func add(x: N, y: N) -> N { return x + y }
public func multiply(x: N, y: N) -> N { return x * y }
}
public let nint32 = NInt32()
public class NInt32: Num {
public typealias N = Int32
public func zero() -> N { return 0 }
public func succ(n: N) -> N { return n + 1 }
public func add(x: N, y: N) -> N { return x + y }
public func multiply(x: N, y: N) -> N { return x * y }
}
public let nint64 = NInt64()
public class NInt64: Num {
public typealias N = Int64
public func zero() -> N { return 0 }
public func succ(n: N) -> N { return n + 1 }
public func add(x: N, y: N) -> N { return x + y }
public func multiply(x: N, y: N) -> N { return x * y }
}
public let nuint8 = NUInt8()
public class NUInt8: Num {
public typealias N = UInt8
public func zero() -> N { return 0 }
public func succ(n: N) -> N { return n + 1 }
public func add(x: N, y: N) -> N { return x + y }
public func multiply(x: N, y: N) -> N { return x * y }
}
public let nuint16 = NUInt16()
public class NUInt16: Num {
public typealias N = UInt16
public func zero() -> N { return 0 }
public func succ(n: N) -> N { return n + 1 }
public func add(x: N, y: N) -> N { return x + y }
public func multiply(x: N, y: N) -> N { return x * y }
}
public let nuint32 = NUInt32()
public class NUInt32: Num {
public typealias N = UInt32
public func zero() -> N { return 0 }
public func succ(n: N) -> N { return n + 1 }
public func add(x: N, y: N) -> N { return x + y }
public func multiply(x: N, y: N) -> N { return x * y }
}
public let nuint64 = NUInt64()
public class NUInt64: Num {
public typealias N = UInt64
public func zero() -> N { return 0 }
public func succ(n: N) -> N { return n + 1 }
public func add(x: N, y: N) -> N { return x + y }
public func multiply(x: N, y: N) -> N { return x * y }
}
| bsd-3-clause | 30dac3a630e8eddf90b838990e9c5bfa | 27.94382 | 61 | 0.588898 | 2.837004 | false | false | false | false |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.