repo_name
stringlengths 7
91
| path
stringlengths 8
658
| copies
stringclasses 125
values | size
stringlengths 3
6
| content
stringlengths 118
674k
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 6.09
99.2
| line_max
int64 17
995
| alpha_frac
float64 0.3
0.9
| ratio
float64 2
9.18
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
swift-lang/swift-k | tests/language-behaviour/mappers/07555-ext-mapper-twostruct.swift | 2 | 428 | type file;
type structInner {
file links;
file rechts;
}
type struct {
file eerste;
file twede;
structInner derde;
};
(file t) write(string s) {
app {
echo s stdout=@filename(t);
}
}
struct outfiles <ext; exec="./07555-ext-mapper-twostruct.sh.in">;
outfiles.eerste = write("1st");
outfiles.twede = write("2nd");
outfiles.derde.links = write("3l");
outfiles.derde.rechts = write("3r");
| apache-2.0 | 6223d4aded355d802b62c9bed701a4f1 | 15.461538 | 65 | 0.628505 | 2.74359 | false | false | false | false |
softdevstory/yata | yata/Sources/Views/EditorView.swift | 1 | 6943 | //
// EditorView.swift
// yata
//
// Created by HS Song on 2017. 7. 6..
// Copyright © 2017년 HS Song. All rights reserved.
//
import Cocoa
class EditorView: NSTextView {
override func viewDidMoveToWindow() {
super.viewDidMoveToWindow()
// delegate = self
resetText()
}
func resetText() {
string = ""
font = NSFont.systemFont(ofSize: NSFont.systemFontSize())
typingAttributes = TextStyles.body.attributes
}
// Prevent paste unkown styles
override func paste(_ sender: Any?) {
super.pasteAsPlainText(sender)
}
}
// MARK: style
extension EditorView {
private func isBoldFont(range: NSRange) -> Bool {
if range.location == textStorage?.length {
if let font = typingAttributes[NSFontAttributeName] as? NSFont {
return font.isBold
} else {
return false
}
}
if let fontAttr = textStorage?.fontAttributes(in: range),
let font = fontAttr[NSFontAttributeName] as? NSFont {
return font.isBold
}
return false
}
private func isItalicFont(range: NSRange) -> Bool {
if range.location == textStorage?.length {
if let font = typingAttributes[NSFontAttributeName] as? NSFont {
return font.isItalic
} else {
return false
}
}
if let fontAttr = textStorage?.fontAttributes(in: range),
let font = fontAttr[NSFontAttributeName] as? NSFont {
return font.isItalic
}
// ??
return false
}
func isBold() -> Bool {
guard let textStorage = textStorage, textStorage.length > 0 else {
return false
}
let paragraphStyle = currentParagraphStyle()
switch paragraphStyle {
case .body, .blockQuote, .pullQuote:
let range = selectedRange()
return isBoldFont(range: range)
default:
return false
}
}
func isItalic() -> Bool {
guard let textStorage = textStorage, textStorage.length > 0 else {
return false
}
let paragraphStyle = currentParagraphStyle()
switch paragraphStyle {
case .body:
let range = selectedRange()
return isItalicFont(range: range)
default:
return false
}
}
func toggleBoldStyle() {
changeSelectedStyle() { (storage, range) in
if isBoldFont(range: range) {
storage.applyFontTraits(.unboldFontMask, range: range)
} else {
storage.applyFontTraits(.boldFontMask, range: range)
}
}
}
func toggleItalicStyle() {
changeSelectedStyle() { (storage, range) in
if isItalicFont(range: range) {
storage.applyFontTraits(.unitalicFontMask, range: range)
} else {
storage.applyFontTraits(.italicFontMask, range: range)
}
}
}
func setLink(link: String) {
changeSelectedStyle() { (storage, range) in
storage.addAttribute(NSLinkAttributeName, value: link, range: range)
}
}
func deleteLink() {
changeSelectedStyle() { (storage, range) in
storage.removeAttribute(NSLinkAttributeName, range: range)
}
}
func getCurrentLink() -> String? {
guard let textStorage = textStorage, textStorage.length > 0 else {
return nil
}
var range = selectedRange()
if range.location == textStorage.length {
return typingAttributes[NSLinkAttributeName] as? String
}
return textStorage.attribute(NSLinkAttributeName, at: range.location, effectiveRange: &range) as? String
}
func setTitleStyle() {
changeParagraphStyle(style: TextStyles.title.attributes)
}
func setHeaderStyle() {
changeParagraphStyle(style: TextStyles.header.attributes)
}
func setBodyStyle() {
changeParagraphStyle(style: TextStyles.body.attributes)
}
func setBlockQuoteStyle() {
changeParagraphStyle(style: TextStyles.blockQuote.attributes)
}
func setPullQuoteStyle() {
changeParagraphStyle(style: TextStyles.pullQuote.attributes)
}
func currentParagraphStyle() -> TextStyles {
guard let storage = textStorage else {
return TextStyles.unknown
}
let range = selectedRange()
let nsString = storage.string as NSString?
if var paragraphRange = nsString?.paragraphRange(for: range) {
if paragraphRange.length == 0 {
return TextStyles.unknown
}
let attrs = storage.attributes(at: paragraphRange.location, effectiveRange: ¶graphRange)
return TextStyles(attributes: attrs)
}
return TextStyles.unknown
}
}
// MARK: support redo / undo
extension EditorView {
fileprivate func changeSelectedStyle(work: (_ storage: NSTextStorage, _ range: NSRange) -> Void) {
guard let storage = textStorage else {
return
}
let range = selectedRange()
if shouldChangeText(in: range, replacementString: nil) {
storage.beginEditing()
work(storage, range)
storage.endEditing()
didChangeText()
}
}
fileprivate func changeParagraphStyle(style: [String: Any]) {
guard let storage = textStorage else {
return
}
let range = selectedRange()
let nsString = storage.string as NSString?
if let paragraphRange = nsString?.paragraphRange(for: range) {
if shouldChangeText(in: paragraphRange, replacementString: nil) {
storage.beginEditing()
storage.setAttributes(style, range: paragraphRange)
storage.endEditing()
didChangeText()
}
}
}
}
//extension EditorView: NSTextViewDelegate {
// func textViewDidChangeSelection(_ notification: Notification) {
// let paragraphStyle = currentParagraphStyle()
// switch paragraphStyle {
// case .unknown:
// Swift.print("unkonwn")
// case .title:
// Swift.print("title")
// case .header:
// Swift.print("header")
// case .body:
// Swift.print("body")
// case .blockQuote:
// Swift.print("blockquote")
// case .pullQuote:
// Swift.print("pullQuote")
// }
// }
//}
| mit | 3bc8db4de3ddc5f9b891a43ffe6d8780 | 25.795367 | 112 | 0.555764 | 5.249622 | false | false | false | false |
JTWang4778/LearningSwiftDemos | 11-循环引用解决/12-类型转换/ViewController.swift | 1 | 2148 | //
// ViewController.swift
// 12-类型转换
//
// Created by 王锦涛 on 2017/5/2.
// Copyright © 2017年 JTWang. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
testAntAndAnyobject()
}
func testAntAndAnyobject() {
/*
Any : 代表任何数据类型 包括值类型和 类类型
AnyObject: 代表任何类类型的实例
*/
var movies:[AnyObject]
movies = [Movie(name: "千与千寻", director: "宫崎骏"),Movie(name: "阿萨德", director: "宫ads骏"),Movie(name: "熟读与激情", director: "宫崎骏")]
// 当已经知道数组中存放的什么类型的实例时 可以强制转换
for item in movies {
let movie = item as! Movie
print("\(movie.name) \(movie.director)")
}
for movie in movies as! [Movie] {
print("\(movie.name) \(movie.director)")
}
}
func testIsAndAs() {
let arr = [Movie(name: "千与千寻", director: "宫崎骏"),Movie(name: "千与千寻", director: "宫崎骏"),Movie(name: "熟读与激情", director: "宫崎骏"),Song(name: "You are beautiful!", artist: "James blunt"),Song(name: "朵", artist: "赵雷")]
var movieCount = 0
var songCount = 0
// 判断类型 is
for item in arr {
if item is Movie {
movieCount += 1
}else if item is Song {
songCount += 1
}
}
print("Movie:\(movieCount) Song:\(songCount)")
// 向下转型 as as? as!
for item in arr {
if let movie = item as? Movie {
print(movie.director)
}else if let song = item as? Song {
print(song.artist)
}
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| mit | 807a55767697a9ec4ee16519eb056421 | 24.613333 | 217 | 0.50026 | 3.759295 | false | false | false | false |
wikimedia/wikipedia-ios | Wikipedia/Code/Article as a Living Document/ArticleAsLivingDocSmallEventCollectionViewCell.swift | 1 | 3999 | import UIKit
class ArticleAsLivingDocSmallEventCollectionViewCell: CollectionViewCell {
private let descriptionLabel = UILabel()
let timelineView = TimelineView()
private var theme: Theme?
private var smallEvent: ArticleAsLivingDocViewModel.Event.Small?
weak var delegate: ArticleDetailsShowing?
override func reset() {
super.reset()
descriptionLabel.text = nil
}
override func setup() {
super.setup()
contentView.addSubview(descriptionLabel)
timelineView.decoration = .squiggle
contentView.addSubview(timelineView)
descriptionLabel.numberOfLines = 1
let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(tappedSmallChanges))
descriptionLabel.addGestureRecognizer(tapGestureRecognizer)
descriptionLabel.isUserInteractionEnabled = true
}
override func sizeThatFits(_ size: CGSize, apply: Bool) -> CGSize {
if traitCollection.horizontalSizeClass == .compact {
layoutMarginsAdditions = UIEdgeInsets(top: 0, left: -5, bottom: 20, right: 0)
} else {
layoutMarginsAdditions = UIEdgeInsets(top: 0, left: 0, bottom: 20, right: 0)
}
let layoutMargins = calculatedLayoutMargins
let timelineTextSpacing: CGFloat = 5
let timelineWidth: CGFloat = 15
let x = layoutMargins.left + timelineWidth + timelineTextSpacing
let widthToFit = size.width - layoutMargins.right - x
if apply {
timelineView.frame = CGRect(x: layoutMargins.left, y: 0, width: timelineWidth, height: size.height)
}
let descriptionOrigin = CGPoint(x: x + 3, y: layoutMargins.top)
let descriptionFrame = descriptionLabel.wmf_preferredFrame(at: descriptionOrigin, maximumSize: CGSize(width: widthToFit, height: UIView.noIntrinsicMetric), minimumSize: NoIntrinsicSize, alignedBy: .forceLeftToRight, apply: apply)
let finalHeight = descriptionFrame.maxY + layoutMargins.bottom
return CGSize(width: size.width, height: finalHeight)
}
func configure(viewModel: ArticleAsLivingDocViewModel.Event.Small, theme: Theme) {
self.smallEvent = viewModel
descriptionLabel.text = viewModel.eventDescription
apply(theme: theme)
setNeedsLayout()
}
override func layoutSublayers(of layer: CALayer) {
super.layoutSublayers(of: layer)
timelineView.dotsY = descriptionLabel.convert(descriptionLabel.bounds, to: timelineView).midY
}
override func updateFonts(with traitCollection: UITraitCollection) {
super.updateFonts(with: traitCollection)
descriptionLabel.font = UIFont.wmf_font(.italicSubheadline, compatibleWithTraitCollection: traitCollection)
}
@objc private func tappedSmallChanges() {
guard let revisionID = smallEvent?.smallChanges.first?.revId,
let parentId = smallEvent?.smallChanges.last?.parentId else {
return
}
if let loggingPosition = smallEvent?.loggingPosition {
ArticleAsLivingDocFunnel.shared.logModalSmallEventsLinkTapped(position: loggingPosition)
}
let diffType: DiffContainerViewModel.DiffType = (smallEvent?.smallChanges.count ?? 0) > 1 ? .compare : .single
delegate?.goToDiff(revisionId: revisionID, parentId: parentId, diffType: diffType)
}
}
extension ArticleAsLivingDocSmallEventCollectionViewCell: Themeable {
func apply(theme: Theme) {
if let oldTheme = self.theme,
theme.webName == oldTheme.webName {
return
}
self.theme = theme
descriptionLabel.textColor = theme.colors.link
timelineView.backgroundColor = theme.colors.paperBackground
timelineView.tintColor = theme.colors.accent
}
}
| mit | 6f21a2e7193b9f3705b89056f66fd1a6 | 36.373832 | 237 | 0.666667 | 5.493132 | false | false | false | false |
wdkk/CAIM | Basic/answer/caim05_1effect_A/basic/DrawingViewController.swift | 1 | 4314 | //
// DrawingViewController.swift
// CAIM Project
// https://kengolab.net/CreApp/wiki/
//
// Copyright (c) Watanabe-DENKI Inc.
// https://wdkk.co.jp/
//
// This software is released under the MIT License.
// https://opensource.org/licenses/mit-license.php
//
import UIKit
class DrawingViewController : CAIMViewController
{
// view_allを画面いっぱいのピクセル領域(screenPixelRect)の大きさで用意
var view_all:CAIMView = CAIMView(pixelFrame: CAIM.screenPixelRect)
// 画像データimg_allを画面のピクセルサイズ(screenPixelSize)に合わせて用意
var img_all:CAIMImage = CAIMImage(size: CAIM.screenPixelSize)
// パーティクル情報の構造体
struct Particle {
var cx:Int = 0
var cy:Int = 0
var radius:Int = 0
var color:CAIMColor = CAIMColor(R: 0.0, G: 0.0, B: 0.0, A: 1.0)
var step:Float = 0.0
}
// パーティクル群を保存しておく配列
var parts:[Particle] = [Particle]()
// 新しいパーティクル情報を作り、返す関数
func generateParticle() -> Particle {
let wid:Int = img_all.width
let hgt:Int = img_all.height
// 位置(cx,cy)、半径(radius)、色(color)を指定した範囲のランダム値で設定
var p = Particle()
p.cx = Int(arc4random()) % wid
p.cy = Int(arc4random()) % hgt
p.radius = Int(arc4random()) % 40 + 20
p.color = CAIMColor(
R: Float(arc4random() % 1000)/1000.0,
G: Float(arc4random() % 1000)/1000.0,
B: Float(arc4random() % 1000)/1000.0,
A: 1.0)
// 作成したパーティクル情報を返す
return p
}
// 準備
override func setup() {
// img_allを白で塗りつぶす
img_all.fillColor( CAIMColor.white )
// view_allの画像として、img_allを設定する
view_all.image = img_all
// view_allを画面に追加
self.view.addSubview( view_all )
// パーティクルを20個作成
for _ in 0 ..< 20 {
var p = generateParticle()
p.step = Float(arc4random() % 1000)/1000.0
parts.append(p)
}
}
// ポーリング
override func update() {
// 毎フレームごと、はじめにimg_allを白で塗りつぶす
img_all.fillColor( CAIMColor.white )
// parts内のパーティクル情報をすべてスキャンする
for i in 0 ..< parts.count {
// 1回処理をするごとにstepを0.01足す
parts[i].step += 0.01
// stepがマイナスの値の場合処理せず、次のパーティクルに移る
if(parts[i].step < 0.0) { continue }
// stepが1.0以上になったら、現在のパーティクル(parts[i])は処理を終えたものとする
// 次に、parts[i]はgenerateParticle()から新しいパーティクル情報を受け取り、新パーティクルとして再始動する
// parts[i]のstepを0.0に戻して初期化したのち、この処理は中断して次のパーティクルに移る
if(parts[i].step >= 1.0) {
parts[i] = generateParticle()
parts[i].step = 0.0
continue
}
// 不透明度(opacity)はstep=0.0~0.5の増加に合わせて最大まで濃くなり、0.5~1.0までに最小まで薄くなる
var opacity:Float = 0.0
if(parts[i].step < 0.5) { opacity = parts[i].step * 2.0 }
else { opacity = (1.0 - parts[i].step) * 2.0 }
// 半径は基本半径(parts[i].radius)にstepと係数2.0を掛け算する
let radius:Int = Int(Float(parts[i].radius) * parts[i].step * 2.0)
// パーティクル情報から求めた計算結果を用いてドームを描く
ImageToolBox.fillDomeFast(img_all, cx: parts[i].cx, cy: parts[i].cy,
radius: radius, color: parts[i].color, opacity: opacity)
}
// 画像が更新されている可能性があるので、view_allを再描画して結果を表示
view_all.redraw()
}
}
| mit | 9bf6b759e4ba586f77c360ac3a938db5 | 30.155963 | 80 | 0.555948 | 2.806612 | false | false | false | false |
headione/criticalmaps-ios | CriticalMapsKit/Sources/MapFeature/RiderAnnotationUpdateClient.swift | 1 | 1385 | import Foundation
import MapKit
import SharedModels
/// A client to update rider annotations on a map.
public struct RiderAnnotationUpdateClient {
/// Calculates the difference between displayed annotations and a collection of new rider elements.
///
/// - Parameters:
/// - riderCoordinates: Collection of rider elements that should be displayed
/// - mapView: A MapView in which the annotations should be displayed
/// - Returns: A tuple containing annotations that should be added and removed
public static func update(
_ riderCoordinates: [Rider],
_ mapView: MKMapView)
-> (
removedAnnotations: [RiderAnnotation],
addedAnnotations: [RiderAnnotation]
) {
let currentlyDisplayedPOIs = mapView.annotations.compactMap { $0 as? RiderAnnotation }
.map { $0.rider }
// Riders that should be added
let addedRider = Set(riderCoordinates).subtracting(currentlyDisplayedPOIs)
// Riders that are not on the map anymore
let removedRider = Set(currentlyDisplayedPOIs).subtracting(riderCoordinates)
let addedAnnotations = addedRider.map(RiderAnnotation.init(rider:))
// Annotations that should be removed
let removedAnnotations = mapView.annotations
.compactMap { $0 as? RiderAnnotation }
.filter { removedRider.contains($0.rider) }
return (removedAnnotations, addedAnnotations)
}
}
| mit | 1d63b6aecab93a80c90b696ed7054048 | 36.432432 | 101 | 0.72491 | 4.694915 | false | false | false | false |
zvonler/PasswordElephant | external/github.com/apple/swift-protobuf/Sources/protoc-gen-swift/Descriptor+Extensions.swift | 4 | 9576 | // Sources/protoc-gen-swift/Descriptor+Extensions.swift - Additions to Descriptors
//
// Copyright (c) 2014 - 2017 Apple Inc. and the project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See LICENSE.txt for license information:
// https://github.com/apple/swift-protobuf/blob/master/LICENSE.txt
//
// -----------------------------------------------------------------------------
import SwiftProtobufPluginLibrary
extension FileDescriptor {
/// True if this file should perserve unknown enums within the enum.
var hasUnknownEnumPreservingSemantics: Bool {
return syntax == .proto3
}
/// True of primative field types should have field presence.
var hasPrimativeFieldPresence: Bool {
return syntax == .proto2
}
var isBundledProto: Bool {
return SwiftProtobufInfo.isBundledProto(file: proto)
}
}
extension Descriptor {
/// Returns True if this is the Any WKT
var isAnyMessage: Bool {
return (file.syntax == .proto3 &&
fullName == ".google.protobuf.Any" &&
file.name == "google/protobuf/any.proto")
}
/// Returns True if this message recurisvely contains a required field.
/// This is a helper for generating isInitialized methods.
///
/// The logic for this check comes from google/protobuf; the C++ and Java
/// generators specificly.
func hasRequiredFields() -> Bool {
var alreadySeen = Set<String>()
func hasRequiredFieldsInner(_ descriptor: Descriptor) -> Bool {
if alreadySeen.contains(descriptor.fullName) {
// First required thing found causes this to return true, so one can
// assume if it is already visited, it didn't have required fields.
return false
}
alreadySeen.insert(descriptor.fullName)
// If it can support extensions, then return true as the extension could
// have a required field.
if !descriptor.extensionRanges.isEmpty {
return true
}
for f in descriptor.fields {
if f.label == .required {
return true
}
switch f.type {
case .group, .message:
if hasRequiredFieldsInner(f.messageType) {
return true
}
default:
break
}
}
return false
}
return hasRequiredFieldsInner(self)
}
/// A `String` containing a comma-delimited list of Swift range expressions
/// covering the extension ranges for this message.
///
/// This expression list is suitable as a pattern match in a `case`
/// statement. For example, `"case 5..<10, 20..<30:"`.
var swiftExtensionRangeExpressions: String {
return extensionRanges.lazy.map {
$0.swiftRangeExpression
}.joined(separator: ", ")
}
/// A `String` containing a Swift Boolean expression that tests if the given
/// variable is in any of the extension ranges for this message.
///
/// - Parameter variable: The name of the variable to test in the expression.
/// - Returns: A `String` containing the Boolean expression.
func swiftExtensionRangeBooleanExpression(variable: String) -> String {
return extensionRanges.lazy.map {
"(\($0.swiftBooleanExpression(variable: variable)))"
}.joined(separator: " || ")
}
}
extension FieldDescriptor {
/// True if this field should have presence support
var hasFieldPresence: Bool {
if label == .repeated { // Covers both Arrays and Maps
return false
}
if oneofIndex != nil {
// When in a oneof, no presence is provided.
return false
}
switch type {
case .group, .message:
// Groups/messages always get field presence.
return true
default:
// Depends on the context the message was declared in.
return file.hasPrimativeFieldPresence
}
}
func swiftType(namer: SwiftProtobufNamer) -> String {
if isMap {
let mapDescriptor: Descriptor = messageType
let keyField = mapDescriptor.fields[0]
let keyType = keyField.swiftType(namer: namer)
let valueField = mapDescriptor.fields[1]
let valueType = valueField.swiftType(namer: namer)
return "Dictionary<" + keyType + "," + valueType + ">"
}
let result: String
switch type {
case .double: result = "Double"
case .float: result = "Float"
case .int64: result = "Int64"
case .uint64: result = "UInt64"
case .int32: result = "Int32"
case .fixed64: result = "UInt64"
case .fixed32: result = "UInt32"
case .bool: result = "Bool"
case .string: result = "String"
case .group: result = namer.fullName(message: messageType)
case .message: result = namer.fullName(message: messageType)
case .bytes: result = "Data"
case .uint32: result = "UInt32"
case .enum: result = namer.fullName(enum: enumType)
case .sfixed32: result = "Int32"
case .sfixed64: result = "Int64"
case .sint32: result = "Int32"
case .sint64: result = "Int64"
}
if label == .repeated {
return "[\(result)]"
}
return result
}
func swiftStorageType(namer: SwiftProtobufNamer) -> String {
let swiftType = self.swiftType(namer: namer)
switch label {
case .repeated:
return swiftType
case .optional, .required:
if hasFieldPresence {
return "\(swiftType)?"
} else {
return swiftType
}
}
}
var protoGenericType: String {
precondition(!isMap)
switch type {
case .double: return "Double"
case .float: return "Float"
case .int64: return "Int64"
case .uint64: return "UInt64"
case .int32: return "Int32"
case .fixed64: return "Fixed64"
case .fixed32: return "Fixed32"
case .bool: return "Bool"
case .string: return "String"
case .group: return "Group"
case .message: return "Message"
case .bytes: return "Bytes"
case .uint32: return "UInt32"
case .enum: return "Enum"
case .sfixed32: return "SFixed32"
case .sfixed64: return "SFixed64"
case .sint32: return "SInt32"
case .sint64: return "SInt64"
}
}
func swiftDefaultValue(namer: SwiftProtobufNamer) -> String {
if isMap {
return "[:]"
}
if label == .repeated {
return "[]"
}
if let defaultValue = explicitDefaultValue {
switch type {
case .double:
switch defaultValue {
case "inf": return "Double.infinity"
case "-inf": return "-Double.infinity"
case "nan": return "Double.nan"
default: return defaultValue
}
case .float:
switch defaultValue {
case "inf": return "Float.infinity"
case "-inf": return "-Float.infinity"
case "nan": return "Float.nan"
default: return defaultValue
}
case .string:
return stringToEscapedStringLiteral(defaultValue)
case .bytes:
return escapedToDataLiteral(defaultValue)
case .enum:
let enumValue = enumType.value(named: defaultValue)!
return namer.dottedRelativeName(enumValue: enumValue)
default:
return defaultValue
}
}
switch type {
case .bool: return "false"
case .string: return "String()"
case .bytes: return "SwiftProtobuf.Internal.emptyData"
case .group, .message:
return namer.fullName(message: messageType) + "()"
case .enum:
return namer.dottedRelativeName(enumValue: enumType.defaultValue)
default:
return "0"
}
}
/// Calculates the traits type used for maps and extensions, they
/// are used in decoding and visiting.
func traitsType(namer: SwiftProtobufNamer) -> String {
if isMap {
let mapDescriptor: Descriptor = messageType
let keyField = mapDescriptor.fields[0]
let keyTraits = keyField.traitsType(namer: namer)
let valueField = mapDescriptor.fields[1]
let valueTraits = valueField.traitsType(namer: namer)
switch valueField.type {
case .message: // Map's can't have a group as the value
return "SwiftProtobuf._ProtobufMessageMap<\(keyTraits),\(valueTraits)>"
case .enum:
return "SwiftProtobuf._ProtobufEnumMap<\(keyTraits),\(valueTraits)>"
default:
return "SwiftProtobuf._ProtobufMap<\(keyTraits),\(valueTraits)>"
}
}
switch type {
case .double: return "SwiftProtobuf.ProtobufDouble"
case .float: return "SwiftProtobuf.ProtobufFloat"
case .int64: return "SwiftProtobuf.ProtobufInt64"
case .uint64: return "SwiftProtobuf.ProtobufUInt64"
case .int32: return "SwiftProtobuf.ProtobufInt32"
case .fixed64: return "SwiftProtobuf.ProtobufFixed64"
case .fixed32: return "SwiftProtobuf.ProtobufFixed32"
case .bool: return "SwiftProtobuf.ProtobufBool"
case .string: return "SwiftProtobuf.ProtobufString"
case .group, .message: return namer.fullName(message: messageType)
case .bytes: return "SwiftProtobuf.ProtobufBytes"
case .uint32: return "SwiftProtobuf.ProtobufUInt32"
case .enum: return namer.fullName(enum: enumType)
case .sfixed32: return "SwiftProtobuf.ProtobufSFixed32"
case .sfixed64: return "SwiftProtobuf.ProtobufSFixed64"
case .sint32: return "SwiftProtobuf.ProtobufSInt32"
case .sint64: return "SwiftProtobuf.ProtobufSInt64"
}
}
}
extension EnumDescriptor {
// True if this enum should perserve unknown enums within the enum.
var hasUnknownPreservingSemantics: Bool {
return file.hasUnknownEnumPreservingSemantics
}
func value(named: String) -> EnumValueDescriptor? {
for v in values {
if v.name == named {
return v
}
}
return nil
}
}
| gpl-3.0 | f43fd144a9be58ade69e31f71f2d9266 | 30.708609 | 82 | 0.6533 | 4.329114 | false | false | false | false |
YevhenHerasymenko/SwiftGroup1 | Operations/Operations/ViewController.swift | 1 | 1092 | //
// ViewController.swift
// Operations
//
// Created by Yevhen Herasymenko on 19/07/2016.
// Copyright © 2016 Yevhen Herasymenko. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let blockOperation = NSBlockOperation {
}
let operationQueue = NSOperationQueue()
let sumOperation = MySumOperation(a: 5, b: 6)
let resultOperation = MyResultOperation()
sumOperation.completionBlock = {
resultOperation.result = sumOperation.sum
}
resultOperation.completionBlock = {
dispatch_async(dispatch_get_main_queue(), {
self.view.backgroundColor = UIColor.greenColor()
})
NSOperationQueue.mainQueue().addOperationWithBlock({
})
}
resultOperation.addDependency(sumOperation)
operationQueue.addOperation(sumOperation)
operationQueue.addOperation(resultOperation)
}
}
| apache-2.0 | 9200707d09fb1c12c0d2a0c4933b91cb | 26.275 | 65 | 0.606783 | 5.482412 | false | false | false | false |
GuoMingJian/DouYuZB | DYZB/DYZB/Classes/Home/Controller/HomeViewController.swift | 1 | 3770 | //
// HomeViewController.swift
// DYZB
//
// Created by 郭明健 on 2017/9/13.
// Copyright © 2017年 com.joy.www. All rights reserved.
//
import UIKit
private var kTitleViewH : CGFloat = 45
class HomeViewController: UIViewController {
//MARK:- 懒加载属性
lazy var pageTitleView : PageTitleView = {[weak self] in
let titleFrame = CGRect(x: 0, y: kNavigationH, width: kScreenW, height: kTitleViewH)
let titles = ["推荐", "游戏", "娱乐", "趣玩"]
let titileView = PageTitleView(frame: titleFrame, titles: titles)
titileView.delegate = self
return titileView
}()
lazy var pageContentView : PageContentView = {[weak self] in
//1.确定内容frame
let contentH = kScreenH - kNavigationH - kTitleViewH - kTabBarH
let contentFrame = CGRect(x: 0, y: kNavigationH + kTitleViewH, width: kScreenW, height: contentH)
//2.确定所有的子控制器
var childVcs = [UIViewController]()
childVcs.append(RecommendViewController())
childVcs.append(GameViewController())
childVcs.append(AmuseViewController())
for _ in 0..<1 {
let vc = UIViewController()
vc.view.backgroundColor = UIColor(r: CGFloat(arc4random_uniform(255)), g: CGFloat(arc4random_uniform(255)), b: CGFloat(arc4random_uniform(255)))
childVcs.append(vc)
}
let contentView = PageContentView(frame: contentFrame, childVcs: childVcs, parentViewController: self)
contentView.delegate = self
return contentView
}()
//MARK:- 系统回调函数
override func viewDidLoad() {
super.viewDidLoad()
//设置UI界面
setupUI()
print(kStatusBarH)
print(kNavigationBarH)
print(kNavigationH)
print(kTabBarH)
}
}
//MARK: 设置UI界面
extension HomeViewController {
func setupUI() {
//不需要调整UIScrollView的内边距
self.automaticallyAdjustsScrollViewInsets = false
//1.设置导航栏
setupNavigationBar()
//2.添加PageTitleView
view.addSubview(pageTitleView)
//3.添加contentView
view.addSubview(pageContentView)
}
func setupNavigationBar() {
//logo
self.navigationItem.leftBarButtonItem = UIBarButtonItem(imageName: "logo")
let size = CGSize(width: 40, height: 40)
//历史记录
let historyItem = UIBarButtonItem(imageName: "image_my_history", highImageName: "Image_my_history_click", size: size)
//搜索
let searchItem = UIBarButtonItem(imageName: "btn_search", highImageName: "btn_search_clicked", size: size)
//二维码
let qrcodeItem = UIBarButtonItem(imageName: "Image_scan", highImageName: "Image_scan_click", size: size)
self.navigationItem.rightBarButtonItems = [historyItem, searchItem, qrcodeItem]
}
}
//MARK:- 遵守PageTitleViewDelegate
extension HomeViewController : PageTitleViewDelegate
{
func pageTitleView(pageTitleView: PageTitleView, selectIndex index: Int)
{
pageContentView.setCurrentIndex(index: index)
}
}
//MARK:- 遵守PageContentViewDelegate
extension HomeViewController : PageContentViewDelegate
{
func pageContentView(contentView: PageContentView, progress: CGFloat, sourceIndex: Int, targetIndex: Int)
{
//print("progress:\(progress) sourceIndex:\(sourceIndex) targetIndex\(targetIndex)")
pageTitleView.setTitleWithProgress(progress: progress, sourceIndex: sourceIndex, targetIndex: targetIndex)
}
}
| mit | 098dffd9a7cbec8faf1b6a459d41a98b | 28.909091 | 156 | 0.634982 | 5.019417 | false | false | false | false |
kkireto/CacheDataManagerSwift | CacheDataManager.swift | 1 | 18814 | //The MIT License (MIT)
//
//Copyright (c) 2014 Kireto
//
//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 Foundation
class CacheDataManager: NSObject {
class var sharedInstance : CacheDataManager {
struct Static {
static var onceToken : dispatch_once_t = 0
static var instance : CacheDataManager? = nil
}
dispatch_once(&Static.onceToken) {
Static.instance = CacheDataManager()
}
return Static.instance!
}
override init () {
super.init()
self.createCacheDirectoryPath()
}
// MARK: - image createCacheDirectoryPaths
private func createCacheDirectoryPath() {
let paths = NSSearchPathForDirectoriesInDomains(.CachesDirectory, .UserDomainMask, true)
let cachePath = paths.first as String
var isDir : ObjCBool = false
if NSFileManager.defaultManager().fileExistsAtPath(cachePath, isDirectory:&isDir) {
if !isDir {
NSFileManager.defaultManager().removeItemAtPath(cachePath, error: nil)
NSFileManager.defaultManager().createDirectoryAtPath(cachePath, withIntermediateDirectories: false, attributes: nil, error: nil)
}
}
else {
NSFileManager.defaultManager().createDirectoryAtPath(cachePath, withIntermediateDirectories: false, attributes: nil, error: nil)
}
}
// MARK: - image cacheDirectoryPath
func cacheDirectoryPath() -> NSString {
let paths = NSSearchPathForDirectoriesInDomains(.CachesDirectory, .UserDomainMask, true)
let cachePath = paths.first as NSString
return cachePath
}
func cacheDirectoryPath(assetId: Int) -> NSString {
var retPath = self.cacheDirectoryPath()
retPath = retPath.stringByAppendingString("\(assetId)")
var isDir : ObjCBool = false
if NSFileManager.defaultManager().fileExistsAtPath(retPath, isDirectory:&isDir) {
if !isDir {
NSFileManager.defaultManager().removeItemAtPath(retPath, error: nil)
NSFileManager.defaultManager().createDirectoryAtPath(retPath, withIntermediateDirectories: false, attributes: nil, error: nil)
}
}
else {
NSFileManager.defaultManager().createDirectoryAtPath(retPath, withIntermediateDirectories: false, attributes: nil, error: nil)
}
return retPath
}
func imageCachePath(imageURL: NSString, assetId: Int) -> NSString {
var retPath = self.cacheDirectoryPath(assetId)
let imageName = imageURL.lastPathComponent
retPath = retPath.stringByAppendingString(imageName)
return retPath
}
// MARK: - set image
func setImage(imageView: UIImageView, assetId: Int, imageURL: NSString, placeholderImage: NSString) {
if imageURL.lastPathComponent.isEmpty {
//prevent getting folder instead of image path error
return
}
let imageCachePath = self.imageCachePath(imageURL, assetId: assetId)
if NSFileManager.defaultManager().fileExistsAtPath(imageCachePath) {
imageView.image = UIImage(contentsOfFile: imageCachePath)
}
else {
if placeholderImage.length > 0 {
imageView.image = UIImage(named: placeholderImage)
}
imageView.tag = assetId
var request = NSMutableURLRequest(URL: NSURL(string: imageURL)!)
request.HTTPShouldHandleCookies = false
var requestOperation = AFHTTPRequestOperation(request: request)
requestOperation.responseSerializer = AFImageResponseSerializer() as AFHTTPResponseSerializer
requestOperation.setCompletionBlockWithSuccess({ (operation, responseObject) -> Void in
if let image = responseObject as? UIImage {
UIImagePNGRepresentation(image).writeToFile(imageCachePath, atomically: true)
if let imgView = imageView as UIImageView? {
if imageView.tag == assetId {
imageView.image = image
}
}
}
}, failure: { (operation, error) -> Void in
println("error downloading button image: " + "\(error)")
})
requestOperation.start()
}
}
func setImage(button: UIButton, assetId: Int, imageURL: NSString, placeholderImage: NSString) {
if imageURL.lastPathComponent.isEmpty {
//prevent getting folder instead of image path error
return
}
let imageCachePath = self.imageCachePath(imageURL, assetId: assetId)
if NSFileManager.defaultManager().fileExistsAtPath(imageCachePath) {
button.setImage(UIImage(contentsOfFile: imageCachePath), forState: UIControlState.Normal)
}
else {
if placeholderImage.length > 0 {
button.setImage(UIImage(named: placeholderImage), forState: UIControlState.Normal)
}
button.tag = assetId
var request = NSMutableURLRequest(URL: NSURL(string: imageURL)!)
request.HTTPShouldHandleCookies = false
var requestOperation = AFHTTPRequestOperation(request: request)
requestOperation.responseSerializer = AFImageResponseSerializer() as AFHTTPResponseSerializer
requestOperation.setCompletionBlockWithSuccess({ (operation, responseObject) -> Void in
if let image = responseObject as? UIImage {
UIImagePNGRepresentation(image).writeToFile(imageCachePath, atomically: true)
if let btn = button as UIButton? {
if button.tag == assetId {
button.setImage(image, forState: UIControlState.Normal)
}
}
}
}, failure: { (operation, error) -> Void in
println("error downloading button image: " + "\(error)")
})
requestOperation.start()
}
}
func setBackgroundImage(button: UIButton, assetId: Int, imageURL: NSString, placeholderImage: NSString) {
if imageURL.lastPathComponent.isEmpty {
//prevent getting folder instead of image path error
return
}
let imageCachePath = self.imageCachePath(imageURL, assetId: assetId)
if NSFileManager.defaultManager().fileExistsAtPath(imageCachePath) {
button.setBackgroundImage(UIImage(contentsOfFile: imageCachePath), forState: UIControlState.Normal)
}
else {
if placeholderImage.length > 0 {
button.setBackgroundImage(UIImage(named: placeholderImage), forState: UIControlState.Normal)
}
button.tag = assetId
var request = NSMutableURLRequest(URL: NSURL(string: imageURL)!)
request.HTTPShouldHandleCookies = false
var requestOperation = AFHTTPRequestOperation(request: request)
requestOperation.responseSerializer = AFImageResponseSerializer() as AFHTTPResponseSerializer
requestOperation.setCompletionBlockWithSuccess({ (operation, responseObject) -> Void in
if let image = responseObject as? UIImage {
UIImagePNGRepresentation(image).writeToFile(imageCachePath, atomically: true)
if let btn = button as UIButton? {
if button.tag == assetId {
button.setBackgroundImage(image, forState: UIControlState.Normal)
}
}
}
}, failure: { (operation, error) -> Void in
println("error downloading button image: " + "\(error)")
})
requestOperation.start()
}
}
// MARK: - set image in background
func setImageInBackground(imageView: UIImageView, assetId: Int, imageURL: NSString, placeholderImage: NSString) {
if imageURL.lastPathComponent.isEmpty {
//prevent getting folder instead of image path error
return
}
let imageCachePath = self.imageCachePath(imageURL, assetId: assetId)
if NSFileManager.defaultManager().fileExistsAtPath(imageCachePath) {
imageView.image = UIImage(contentsOfFile: imageCachePath)
}
else {
if placeholderImage.length > 0 {
imageView.image = UIImage(named: placeholderImage)
}
imageView.tag = assetId
var request = NSMutableURLRequest(URL: NSURL(string: imageURL)!)
request.HTTPShouldHandleCookies = false
var requestOperation = AFHTTPRequestOperation(request: request)
requestOperation.responseSerializer = AFImageResponseSerializer() as AFHTTPResponseSerializer
requestOperation.setCompletionBlockWithSuccess({ (operation, responseObject) -> Void in
if let image = responseObject as? UIImage {
var args = ["image_view":imageView,
"image_path":imageCachePath,
"image":image,
"asset_id": assetId] as NSDictionary
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), { () -> Void in
self.setImageViewImage(args)
})
}
}, failure: { (operation, error) -> Void in
println("error downloading button image: " + "\(error)")
})
requestOperation.start()
}
}
func setImageInBackground(button: UIButton, assetId: Int, imageURL: NSString, placeholderImage: NSString) {
if imageURL.lastPathComponent.isEmpty {
//prevent getting folder instead of image path error
return
}
let imageCachePath = self.imageCachePath(imageURL, assetId: assetId)
if NSFileManager.defaultManager().fileExistsAtPath(imageCachePath) {
button.setImage(UIImage(contentsOfFile: imageCachePath), forState: UIControlState.Normal)
}
else {
if placeholderImage.length > 0 {
button.setImage(UIImage(named: placeholderImage), forState: UIControlState.Normal)
}
button.tag = assetId
var request = NSMutableURLRequest(URL: NSURL(string: imageURL)!)
request.HTTPShouldHandleCookies = false
var requestOperation = AFHTTPRequestOperation(request: request)
requestOperation.responseSerializer = AFImageResponseSerializer() as AFHTTPResponseSerializer
requestOperation.setCompletionBlockWithSuccess({ (operation, responseObject) -> Void in
if let image = responseObject as? UIImage {
var args = ["button":button,
"image_path":imageCachePath,
"image":image,
"asset_id": assetId] as NSDictionary
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), { () -> Void in
self.setButtonImage(args)
})
}
}, failure: { (operation, error) -> Void in
println("error downloading button image: " + "\(error)")
})
requestOperation.start()
}
}
func setBackgroundImageInBackground(button: UIButton, assetId: Int, imageURL: NSString, placeholderImage: NSString) {
if imageURL.lastPathComponent.isEmpty {
//prevent getting folder instead of image path error
return
}
let imageCachePath = self.imageCachePath(imageURL, assetId: assetId)
if NSFileManager.defaultManager().fileExistsAtPath(imageCachePath) {
button.setBackgroundImage(UIImage(contentsOfFile: imageCachePath), forState: UIControlState.Normal)
}
else {
if placeholderImage.length > 0 {
button.setBackgroundImage(UIImage(named: placeholderImage), forState: UIControlState.Normal)
}
button.tag = assetId
var request = NSMutableURLRequest(URL: NSURL(string: imageURL)!)
request.HTTPShouldHandleCookies = false
var requestOperation = AFHTTPRequestOperation(request: request)
requestOperation.responseSerializer = AFImageResponseSerializer() as AFHTTPResponseSerializer
requestOperation.setCompletionBlockWithSuccess({ (operation, responseObject) -> Void in
if let image = responseObject as? UIImage {
var args = ["button":button,
"image_path":imageCachePath,
"image":image,
"asset_id": assetId] as NSDictionary
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), { () -> Void in
self.setButtonBackgroundImage(args)
})
}
}, failure: { (operation, error) -> Void in
println("error downloading button image: " + "\(error)")
})
requestOperation.start()
}
}
// MARK: - background methods
private func setImageViewImage(args:NSDictionary) {
var imageView = args.valueForKey("image_view") as? UIImageView
var imageCachePath = args.valueForKey("image_path") as? NSString
var image = args.valueForKey("image_view") as? UIImage
var assetId = args.valueForKey("asset_id") as? Int
if imageView != nil && imageCachePath != nil && image != nil && assetId != nil {
if imageView!.tag == assetId! {
UIImagePNGRepresentation(image!).writeToFile(imageCachePath!, atomically: true)
if imageView != nil {
if imageView!.tag == assetId! {
//update GUI on main thread
dispatch_async(dispatch_get_main_queue(), {
imageView!.image = image!
})
}
}
}
}
}
private func setButtonImage(args:NSDictionary) {
var button = args.valueForKey("button") as? UIButton
var imageCachePath = args.valueForKey("image_path") as? NSString
var image = args.valueForKey("image_view") as? UIImage
var assetId = args.valueForKey("asset_id") as? Int
if button != nil && imageCachePath != nil && image != nil && assetId != nil {
if button!.tag == assetId! {
UIImagePNGRepresentation(image!).writeToFile(imageCachePath!, atomically: true)
if button != nil {
if button!.tag == assetId! {
//update GUI on main thread
dispatch_async(dispatch_get_main_queue(), {
button!.setImage(image!, forState: UIControlState.Normal)
})
}
}
}
}
}
private func setButtonBackgroundImage(args:NSDictionary) {
var button = args.valueForKey("button") as? UIButton
var imageCachePath = args.valueForKey("image_path") as? NSString
var image = args.valueForKey("image_view") as? UIImage
var assetId = args.valueForKey("asset_id") as? Int
if button != nil && imageCachePath != nil && image != nil && assetId != nil {
if button!.tag == assetId! {
UIImagePNGRepresentation(image!).writeToFile(imageCachePath!, atomically: true)
if button != nil {
if button!.tag == assetId! {
//update GUI on main thread
dispatch_async(dispatch_get_main_queue(), {
button!.setBackgroundImage(image!, forState: UIControlState.Normal)
})
}
}
}
}
}
// MARK: - remove cache data
func removeCachedData(imageURL: NSString, assetId: Int) {
if imageURL.lastPathComponent.isEmpty {
//prevent getting folder instead of image path error
return
}
let path = self.imageCachePath(imageURL, assetId: assetId)
var isDir : ObjCBool = false
if NSFileManager.defaultManager().fileExistsAtPath(path, isDirectory:&isDir) {
if !isDir {
NSFileManager.defaultManager().removeItemAtPath(path, error: nil)
}
}
}
func removeCachedData(assetId: Int) {
let imagesDir = self.cacheDirectoryPath(assetId)
self.emptyDirectory(imagesDir)
}
func removeAllCachedData() {
let dirToEmpty = self.cacheDirectoryPath()
self.emptyDirectory(dirToEmpty)
}
private func emptyDirectory(path: NSString) {
if let files = NSFileManager.defaultManager().contentsOfDirectoryAtPath(path, error: nil) as NSArray? {
for file in files {
let fileName = file as String
let filePath = path.stringByAppendingPathComponent(fileName)
var isDir : ObjCBool = false
if NSFileManager.defaultManager().fileExistsAtPath(filePath, isDirectory:&isDir) {
if isDir {
self.emptyDirectory(filePath)
}
else {
NSFileManager.defaultManager().removeItemAtPath(filePath, error: nil)
}
}
}
}
}
}
| mit | 7a83507917e34ca1e7b33a16c29956b2 | 48.122715 | 144 | 0.602477 | 5.75 | false | false | false | false |
siemensikkema/Fairness | realm-cocoa-0.87.4/examples/ios/swift/TableView/TableViewController.swift | 1 | 4303 | ////////////////////////////////////////////////////////////////////////////
//
// Copyright 2014 Realm 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
import Realm
class DemoObject: RLMObject {
dynamic var title = ""
dynamic var date = NSDate()
}
class Cell: UITableViewCell {
override init(style: UITableViewCellStyle, reuseIdentifier: String!) {
super.init(style: .Subtitle, reuseIdentifier: reuseIdentifier)
}
required init(coder: NSCoder) {
fatalError("NSCoding not supported")
}
}
class TableViewController: UITableViewController {
var array = DemoObject.allObjects()
var notificationToken: RLMNotificationToken?
override func viewDidLoad() {
super.viewDidLoad()
setupUI()
// Set realm notification block
notificationToken = RLMRealm.defaultRealm().addNotificationBlock { note, realm in
self.reloadData()
}
reloadData()
}
// UI
func setupUI() {
tableView.registerClass(Cell.self, forCellReuseIdentifier: "cell")
self.title = "SwiftExample"
self.navigationItem.leftBarButtonItem = UIBarButtonItem(title: "BG Add", style: .Plain, target: self, action: "backgroundAdd")
self.navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .Add, target: self, action: "add")
}
// Table view data source
override func tableView(tableView: UITableView?, numberOfRowsInSection section: Int) -> Int {
return Int(array.count)
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as Cell
let object = array[UInt(indexPath.row)] as DemoObject
cell.textLabel.text = object.title
cell.detailTextLabel?.text = object.date.description
return cell
}
override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if editingStyle == .Delete {
let realm = RLMRealm.defaultRealm()
realm.beginWriteTransaction()
realm.deleteObject(array[UInt(indexPath.row)] as RLMObject)
realm.commitWriteTransaction()
}
}
// Actions
func reloadData() {
array = DemoObject.allObjects().sortedResultsUsingProperty("date", ascending: true)
tableView.reloadData()
}
func backgroundAdd() {
let queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)
// Import many items in a background thread
dispatch_async(queue) {
// Get new realm and table since we are in a new thread
let realm = RLMRealm.defaultRealm()
realm.beginWriteTransaction()
for index in 0..<5 {
// Add row via dictionary. Order is ignored.
DemoObject.createInRealm(realm, withObject: ["title": TableViewController.randomString(), "date": TableViewController.randomDate()])
}
realm.commitWriteTransaction()
}
}
func add() {
let realm = RLMRealm.defaultRealm()
realm.beginWriteTransaction()
DemoObject.createInRealm(realm, withObject: [TableViewController.randomString(), TableViewController.randomDate()])
realm.commitWriteTransaction()
}
// Helpers
class func randomString() -> String {
return "Title \(arc4random())"
}
class func randomDate() -> NSDate {
return NSDate(timeIntervalSince1970: NSTimeInterval(arc4random()))
}
}
| mit | 2b370e63bc9a9e13f089628f313d7578 | 32.617188 | 157 | 0.649547 | 5.345342 | false | false | false | false |
IvanVorobei/Sparrow | sparrow/modules/request-permissions/managers/presenters/dialog/interactive/controller/SPRequestPermissionDialogInteractiveViewController.swift | 2 | 4459 | // The MIT License (MIT)
// Copyright © 2017 Ivan Vorobei ([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
public class SPRequestPermissionDialogInteractiveViewController: SPDialogSwipeController<SPRequestPermissionDialogInteractiveView, UILabel> {
public var presenter: SPRequestPermissionDialogInteractivePresenterDelegate
init(presenter: SPRequestPermissionDialogInteractivePresenterDelegate) {
self.presenter = presenter
super.init(dialogView: SPRequestPermissionDialogInteractiveView())
self.presenter.viewController = self
self.delegate = self
self.dialogViewMaxWidth = 300
self.dialogViewMaxHeight = 450
self.dialogViewWidthRelativeFactor = 0.8
self.dialogViewHeightRelativeFactor = 0.8
self.dialogViewSidesRelativeFactor = 0.667
self.dialogViewPortraitYtranslationFactor = 0.96
self.dialogViewLandscapeYtranslationFactor = 1
self.bottomView.font = UIFont.init(
name: SPRequestPermissionData.fonts.base() + "-Regular",
size: 12
)
self.bottomView.textColor = UIColor.white
self.bottomView.setShadowOffsetForLetters(heightOffset: 1, opacity: 0.4)
self.bottomView.setCenteringAlignment()
self.bottomView.numberOfLines = 0
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override public func viewDidLoad() {
super.viewDidLoad()
self.dialogView.backgroundColor = UIColor.white
}
override public func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
super.viewWillTransition(to: size, with: coordinator)
coordinator.animate(alongsideTransition: { (context) in
self.dialogView.layoutIfNeeded()
}, completion: nil)
}
}
extension SPRequestPermissionDialogInteractiveViewController: SPRequestPermissionDialogInteractiveViewControllerInterface {
public func hide() {
self.hide(withDialog: true)
}
public func addControl(_ control: SPRequestPermissionTwiceControlInterface) {
control.addAsSubviewTo(self.dialogView.buttonsContainerView)
}
public func setHeaderBackgroundView(_ view: UIView) {
self.dialogView.headerView.setBackgroundView(view)
}
public func setHeaderTitle(_ title: String) {
self.dialogView.headerView.titleLabel.text = title
self.dialogView.layoutSubviews()
}
public func setHeaderSubtitle(_ title: String) {
self.dialogView.headerView.subtitleLabel.text = title
self.dialogView.layoutSubviews()
}
public func setTopTitle(_ title: String) {
self.dialogView.topLabel.text = title
self.dialogView.layoutSubviews()
}
public func setBottomTitle(_ title: String) {
self.dialogView.bottomLabel.text = title
self.dialogView.layoutSubviews()
}
public func setUnderDialogTitle(_ title: String) {
self.bottomView.text = title
}
}
extension SPRequestPermissionDialogInteractiveViewController: SPDialogSwipeControllerDelegate {
internal var isEnableHideDialogController: Bool {
return true
}
func didHideDialogController() {
self.presenter.didHide()
}
}
| mit | 3206da3078aab501755989ca1c3e0cd1 | 36.779661 | 141 | 0.715343 | 5.100686 | false | false | false | false |
uraimo/SwiftyGPIO | Sources/I2C.swift | 1 | 15208 | /*
SwiftyGPIO
Copyright (c) 2017 Umberto Raimondi
Licensed under the MIT license, as follows:
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(Linux)
import Glibc
#else
import Darwin.C
#endif
extension SwiftyGPIO {
public static func hardwareI2Cs(for board: SupportedBoard) -> [I2CInterface]? {
switch board {
case .CHIP:
return [I2CCHIP[1]!, I2CCHIP[2]!]
case .RaspberryPiRev1,
.RaspberryPiRev2,
.RaspberryPiPlusZero,
.RaspberryPiZero2,
.RaspberryPi2,
.RaspberryPi3,
.RaspberryPi4:
return [I2CRPI[0]!, I2CRPI[1]!]
default:
return nil
}
}
}
// MARK: - I2C Presets
extension SwiftyGPIO {
// RaspberryPis I2Cs
static let I2CRPI: [Int:I2CInterface] = [
0: SysFSI2C(i2cId: 0),
1: SysFSI2C(i2cId: 1)
]
// CHIP I2Cs
// i2c.0: connected to the AXP209 chip
// i2c.1: after 4.4.13-ntc-mlc connected to the U13 header I2C interface
// i2c.2: connected to the U14 header I2C interface, XIO gpios are connected on this bus
static let I2CCHIP: [Int:I2CInterface] = [
1: SysFSI2C(i2cId: 1),
2: SysFSI2C(i2cId: 2),
]
}
// MARK: I2C
public protocol I2CInterface {
func isReachable(_ address: Int) -> Bool
func setPEC(_ address: Int, enabled: Bool)
func readByte(_ address: Int) -> UInt8
func readByte(_ address: Int, command: UInt8) -> UInt8
func readWord(_ address: Int, command: UInt8) -> UInt16
func readData(_ address: Int, command: UInt8) -> [UInt8]
func readI2CData(_ address: Int, command: UInt8) -> [UInt8]
func writeQuick(_ address: Int)
func writeByte(_ address: Int, value: UInt8)
func writeByte(_ address: Int, command: UInt8, value: UInt8)
func writeWord(_ address: Int, command: UInt8, value: UInt16)
func writeData(_ address: Int, command: UInt8, values: [UInt8])
func writeI2CData(_ address: Int, command: UInt8, values: [UInt8])
// One-shot rd/wr not provided
}
/// Hardware I2C(SMBus) via SysFS using I2C_SMBUS ioctl
public final class SysFSI2C: I2CInterface {
let i2cId: Int
var fd: Int32 = -1
var currentSlave: Int = -1
public init(i2cId: Int) {
self.i2cId=i2cId
}
deinit {
if fd != -1 {
closeI2C()
}
}
public func readByte(_ address: Int) -> UInt8 {
setSlaveAddress(address)
let r = i2c_smbus_read_byte()
if r < 0 {
perror("I2C read failed")
abort()
}
#if swift(>=4.0)
return UInt8(truncatingIfNeeded: r)
#else
return UInt8(truncatingBitPattern: r)
#endif
}
public func readByte(_ address: Int, command: UInt8) -> UInt8 {
setSlaveAddress(address)
let r = i2c_smbus_read_byte_data(command: command)
if r < 0 {
perror("I2C read failed")
abort()
}
#if swift(>=4.0)
return UInt8(truncatingIfNeeded: r)
#else
return UInt8(truncatingBitPattern: r)
#endif
}
public func readWord(_ address: Int, command: UInt8) -> UInt16 {
setSlaveAddress(address)
let r = i2c_smbus_read_word_data(command: command)
if r < 0 {
perror("I2C read failed")
abort()
}
#if swift(>=4.0)
return UInt16(truncatingIfNeeded: r)
#else
return UInt16(truncatingBitPattern: r)
#endif
}
public func readData(_ address: Int, command: UInt8) -> [UInt8] {
var buf: [UInt8] = [UInt8](repeating:0, count: 32)
setSlaveAddress(address)
let r = i2c_smbus_read_block_data(command: command, values: &buf)
if r < 0 {
perror("I2C read failed")
abort()
}
return buf
}
public func readI2CData(_ address: Int, command: UInt8) -> [UInt8] {
var buf: [UInt8] = [UInt8](repeating:0, count: 32)
setSlaveAddress(address)
let r = i2c_smbus_read_i2c_block_data(command: command, values: &buf)
if r < 0 {
perror("I2C read failed")
abort()
}
return buf
}
public func writeQuick(_ address: Int) {
setSlaveAddress(address)
let r = i2c_smbus_write_quick(value: I2C_SMBUS_WRITE)
if r < 0 {
perror("I2C write failed")
abort()
}
}
public func writeByte(_ address: Int, value: UInt8) {
setSlaveAddress(address)
let r = i2c_smbus_write_byte(value: value)
if r < 0 {
perror("I2C write failed")
abort()
}
}
public func writeByte(_ address: Int, command: UInt8, value: UInt8) {
setSlaveAddress(address)
let r = i2c_smbus_write_byte_data(command: command, value: value)
if r < 0 {
perror("I2C write failed")
abort()
}
}
public func writeWord(_ address: Int, command: UInt8, value: UInt16) {
setSlaveAddress(address)
let r = i2c_smbus_write_word_data(command: command, value: value)
if r < 0 {
perror("I2C write failed")
abort()
}
}
public func writeData(_ address: Int, command: UInt8, values: [UInt8]) {
setSlaveAddress(address)
let r = i2c_smbus_write_block_data(command: command, values: values)
if r < 0 {
perror("I2C write failed")
abort()
}
}
public func writeI2CData(_ address: Int, command: UInt8, values: [UInt8]) {
setSlaveAddress(address)
let r = i2c_smbus_write_i2c_block_data(command: command, values: values)
if r < 0 {
perror("I2C write failed")
abort()
}
}
public func isReachable(_ address: Int) -> Bool {
setSlaveAddress(address)
var r: Int32 = -1
// Mimic the behaviour of i2cdetect, performing bogus read/quickwrite depending on the address
switch(address){
case 0x3...0x2f:
r = i2c_smbus_write_quick(value: 0)
case 0x30...0x37:
r = i2c_smbus_read_byte()
case 0x38...0x4f:
r = i2c_smbus_write_quick(value: 0)
case 0x50...0x5f:
r = i2c_smbus_read_byte()
case 0x60...0x77:
r = i2c_smbus_write_quick(value: 0)
default:
r = i2c_smbus_read_byte()
}
guard r >= 0 else { return false }
return true
}
public func setPEC(_ address: Int, enabled: Bool) {
setSlaveAddress(address)
let r = ioctl(fd, I2C_PEC, enabled ? 1 : 0)
if r != 0 {
perror("I2C communication failed")
abort()
}
}
private func setSlaveAddress(_ to: Int) {
if fd == -1 {
openI2C()
}
guard currentSlave != to else {return}
let r = ioctl(fd, I2C_SLAVE_FORCE, CInt(to))
if r != 0 {
perror("I2C communication failed")
abort()
}
currentSlave = to
}
private func openI2C() {
let fd = open(I2CBASEPATH+String(i2cId), O_RDWR)
guard fd > 0 else {
fatalError("Couldn't open the I2C device")
}
self.fd = fd
}
private func closeI2C() {
close(fd)
}
// Private functions
// Swift implementation of the smbus functions provided by i2c-dev
private struct i2c_smbus_ioctl_data {
var read_write: UInt8
var command: UInt8
var size: Int32
var data: UnsafeMutablePointer<UInt8>? //union: UInt8, UInt16, [UInt8]33
}
private func smbus_ioctl(rw: UInt8, command: UInt8, size: Int32, data: UnsafeMutablePointer<UInt8>?) -> Int32 {
if fd == -1 {
openI2C()
}
var args = i2c_smbus_ioctl_data(read_write: rw,
command: command,
size: size,
data: data)
return ioctl(fd, I2C_SMBUS, &args)
}
//
// Read
//
private func i2c_smbus_read_byte() -> Int32 {
var data = [UInt8](repeating:0, count: I2C_DEFAULT_PAYLOAD_LENGTH)
let r = smbus_ioctl(rw: I2C_SMBUS_READ,
command: 0,
size: I2C_SMBUS_BYTE,
data: &data)
if r >= 0 {
return Int32(data[0])
} else {
return -1
}
}
private func i2c_smbus_read_byte_data(command: UInt8) -> Int32 {
var data = [UInt8](repeating:0, count: I2C_DEFAULT_PAYLOAD_LENGTH)
let r = smbus_ioctl(rw: I2C_SMBUS_READ,
command: command,
size: I2C_SMBUS_BYTE_DATA,
data: &data)
if r >= 0 {
return Int32(data[0])
} else {
return -1
}
}
private func i2c_smbus_read_word_data(command: UInt8) -> Int32 {
var data = [UInt8](repeating:0, count: I2C_DEFAULT_PAYLOAD_LENGTH)
let r = smbus_ioctl(rw: I2C_SMBUS_READ,
command: command,
size: I2C_SMBUS_WORD_DATA,
data: &data)
if r >= 0 {
return (Int32(data[1]) << 8) + Int32(data[0])
} else {
return -1
}
}
private func i2c_smbus_read_block_data(command: UInt8, values: inout [UInt8]) -> Int32 {
var data = [UInt8](repeating:0, count: I2C_DEFAULT_PAYLOAD_LENGTH)
let r = smbus_ioctl(rw: I2C_SMBUS_READ,
command: command,
size: I2C_SMBUS_BLOCK_DATA,
data: &data)
if r >= 0 {
for i in 0..<Int(data[0]) {
values[i] = data[i+1]
}
return Int32(data[0])
} else {
return -1
}
}
private func i2c_smbus_read_i2c_block_data(command: UInt8, values: inout [UInt8]) -> Int32 {
var data = [UInt8](repeating:0, count: I2C_DEFAULT_PAYLOAD_LENGTH)
let r = smbus_ioctl(rw: I2C_SMBUS_READ,
command: command,
size: I2C_SMBUS_I2C_BLOCK_DATA,
data: &data)
if r >= 0 {
for i in 0..<Int(data[0]) {
values[i] = data[i+1]
}
return Int32(data[0])
} else {
return -1
}
}
//
// Write
//
private func i2c_smbus_write_quick(value: UInt8) -> Int32 {
return smbus_ioctl(rw: value,
command: 0,
size: I2C_SMBUS_QUICK,
data: nil)
}
private func i2c_smbus_write_byte(value: UInt8) -> Int32 {
return smbus_ioctl(rw: I2C_SMBUS_WRITE,
command: value,
size: I2C_SMBUS_BYTE,
data: nil)
}
private func i2c_smbus_write_byte_data(command: UInt8, value: UInt8) -> Int32 {
var data = [UInt8](repeating:0, count: I2C_DEFAULT_PAYLOAD_LENGTH)
data[0] = value
return smbus_ioctl(rw: I2C_SMBUS_WRITE,
command: command,
size: I2C_SMBUS_BYTE_DATA,
data: &data)
}
private func i2c_smbus_write_word_data(command: UInt8, value: UInt16) -> Int32 {
var data = [UInt8](repeating:0, count: I2C_DEFAULT_PAYLOAD_LENGTH)
data[0] = UInt8(value & 0xFF)
data[1] = UInt8(value >> 8)
return smbus_ioctl(rw: I2C_SMBUS_WRITE,
command: command,
size: I2C_SMBUS_WORD_DATA,
data: &data)
}
private func i2c_smbus_write_block_data(command: UInt8, values: [UInt8]) -> Int32 {
guard values.count<=I2C_DEFAULT_PAYLOAD_LENGTH else { fatalError("Invalid data length, can't send more than \(I2C_DEFAULT_PAYLOAD_LENGTH) bytes!") }
var data = [UInt8](repeating:0, count: values.count+1)
for i in 1...values.count {
data[i] = values[i-1]
}
data[0] = UInt8(values.count)
return smbus_ioctl(rw: I2C_SMBUS_WRITE,
command: command,
size: I2C_SMBUS_BLOCK_DATA,
data: &data)
}
private func i2c_smbus_write_i2c_block_data(command: UInt8, values: [UInt8]) -> Int32 {
guard values.count<=I2C_DEFAULT_PAYLOAD_LENGTH else { fatalError("Invalid data length, can't send more than \(I2C_DEFAULT_PAYLOAD_LENGTH) bytes!") }
var data = [UInt8](repeating:0, count: values.count+1)
for i in 1...values.count {
data[i] = values[i-1]
}
data[0] = UInt8(values.count)
return smbus_ioctl(rw: I2C_SMBUS_WRITE,
command: command,
size: I2C_SMBUS_I2C_BLOCK_DATA,
data: &data)
}
}
// MARK: - I2C/SMBUS Constants
internal let I2C_SMBUS_READ: UInt8 = 1
internal let I2C_SMBUS_WRITE: UInt8 = 0
internal let I2C_SMBUS_QUICK: Int32 = 0
internal let I2C_SMBUS_BYTE: Int32 = 1
internal let I2C_SMBUS_BYTE_DATA: Int32 = 2
internal let I2C_SMBUS_WORD_DATA: Int32 = 3
internal let I2C_SMBUS_BLOCK_DATA: Int32 = 5
//Not implemented: I2C_SMBUS_I2C_BLOCK_BROKEN 6
//Not implemented: I2C_SMBUS_BLOCK_PROC_CALL 7
internal let I2C_SMBUS_I2C_BLOCK_DATA: Int32 = 8
internal let I2C_SLAVE: UInt = 0x703
internal let I2C_SLAVE_FORCE: UInt = 0x706
internal let I2C_RDWR: UInt = 0x707
internal let I2C_PEC: UInt = 0x708
internal let I2C_SMBUS: UInt = 0x720
internal let I2C_DEFAULT_PAYLOAD_LENGTH: Int = 32
internal let I2CBASEPATH="/dev/i2c-"
// MARK: - Darwin / Xcode Support
#if os(OSX) || os(iOS)
private var O_SYNC: CInt { fatalError("Linux only") }
#endif
| mit | 47f04aba0ab525ae1e6237c02f181a85 | 28.359073 | 156 | 0.545568 | 3.498505 | false | false | false | false |
benlangmuir/swift | test/Migrator/Inputs/substring_to_string_conversion.swift | 55 | 1279 | let s = "Hello"
let ss = s[s.startIndex..<s.endIndex]
// CTP_Initialization
do {
let s1: String = { return ss }()
_ = s1
}
// CTP_ReturnStmt
do {
func returnsAString() -> String {
return ss
}
}
// CTP_ThrowStmt
// Doesn't really make sense for this fix-it - see case in diagnoseContextualConversionError:
// The conversion destination of throw is always ErrorType (at the moment)
// if this ever expands, this should be a specific form like () is for
// return.
// CTP_EnumCaseRawValue
// Substrings can't be raw values because they aren't literals.
// CTP_DefaultParameter
do {
func foo(x: String = ss) {}
}
// CTP_CalleeResult
do {
func getSubstring() -> Substring { return ss }
let gottenString : String = getSubstring()
_ = gottenString
}
// CTP_CallArgument
do {
func takesAString(_ s: String) {}
takesAString(ss)
}
// CTP_ClosureResult
do {
[ss].map { (x: Substring) -> String in x }
}
// CTP_ArrayElement
do {
let a: [String] = [ ss ]
_ = a
}
// CTP_DictionaryKey
do {
let d: [ String : String ] = [ ss : s ]
_ = d
}
// CTP_DictionaryValue
do {
let d: [ String : String ] = [ s : ss ]
_ = d
}
// CTP_CoerceOperand
do {
let s1: String = ss as String
_ = s1
}
// CTP_AssignSource
do {
let s1: String = ss
_ = s1
}
| apache-2.0 | 302c899d2997230f65d30bb285114d7e | 15.397436 | 93 | 0.627052 | 3.089372 | false | false | false | false |
rechsteiner/Parchment | ParchmentTests/Mocks/MockCollectionView.swift | 1 | 4216 | @testable import Parchment
import UIKit
final class MockCollectionView: CollectionView, Mock {
enum Action: Equatable {
case contentOffset(CGPoint)
case reloadData
case layoutIfNeeded
case setContentOffset(
contentOffset: CGPoint,
animated: Bool
)
case selectItem(
indexPath: IndexPath?,
animated: Bool,
scrollPosition: UICollectionView.ScrollPosition
)
}
var visibleItems: (() -> Int)!
weak var collectionViewLayout: MockCollectionViewLayout!
var calls: [MockCall] = []
var indexPathsForVisibleItems: [IndexPath] = []
var isDragging: Bool = false
var window: UIWindow?
var superview: UIView?
var bounds: CGRect = .zero
var contentSize: CGSize = .zero
var contentInset: UIEdgeInsets = .zero
var showsHorizontalScrollIndicator: Bool = false
var dataSource: UICollectionViewDataSource?
var isScrollEnabled: Bool = false
var alwaysBounceHorizontal: Bool = false
private var _contentInsetAdjustmentBehavior: Any?
@available(iOS 11.0, *)
var contentInsetAdjustmentBehavior: UIScrollView.ContentInsetAdjustmentBehavior {
get {
if _contentInsetAdjustmentBehavior == nil {
return .never
}
return _contentInsetAdjustmentBehavior as! UIScrollView.ContentInsetAdjustmentBehavior
}
set {
_contentInsetAdjustmentBehavior = newValue
}
}
var contentOffset: CGPoint = .zero {
didSet {
calls.append(MockCall(
datetime: Date(),
action: .collectionView(.contentOffset(contentOffset))
))
}
}
func reloadData() {
calls.append(MockCall(
datetime: Date(),
action: .collectionView(.reloadData)
))
let items = visibleItems()
let range = 0 ..< items
let indexPaths = range.map { IndexPath(item: $0, section: 0) }
contentSize = CGSize(
width: PagingControllerTests.ItemSize * CGFloat(items),
height: PagingControllerTests.ItemSize
)
indexPathsForVisibleItems = indexPaths
var layoutAttributes: [IndexPath: PagingCellLayoutAttributes] = [:]
for indexPath in indexPaths {
let attributes = PagingCellLayoutAttributes(forCellWith: indexPath)
attributes.frame = CGRect(
x: PagingControllerTests.ItemSize * CGFloat(indexPath.item),
y: 0,
width: PagingControllerTests.ItemSize,
height: PagingControllerTests.ItemSize
)
layoutAttributes[indexPath] = attributes
}
collectionViewLayout.layoutAttributes = layoutAttributes
}
func layoutIfNeeded() {
calls.append(MockCall(
datetime: Date(),
action: .collectionView(.layoutIfNeeded)
))
}
func setContentOffset(_ contentOffset: CGPoint, animated: Bool) {
calls.append(MockCall(
datetime: Date(),
action: .collectionView(.setContentOffset(
contentOffset: contentOffset,
animated: animated
))
))
}
func selectItem(at indexPath: IndexPath?, animated: Bool, scrollPosition: UICollectionView.ScrollPosition) {
calls.append(MockCall(
datetime: Date(),
action: .collectionView(.selectItem(
indexPath: indexPath,
animated: animated,
scrollPosition: scrollPosition
))
))
if let indexPath = indexPath {
contentOffset = CGPoint(
x: CGFloat(indexPath.item) * PagingControllerTests.ItemSize,
y: 0
)
}
}
func register(_: AnyClass?, forCellWithReuseIdentifier _: String) {
return
}
func register(_: UINib?, forCellWithReuseIdentifier _: String) {
return
}
func addGestureRecognizer(_: UIGestureRecognizer) {
return
}
func removeGestureRecognizer(_: UIGestureRecognizer) {
return
}
}
| mit | 5fa4d6168ae057d6aee2f7214bdf9afe | 28.900709 | 112 | 0.597723 | 5.954802 | false | false | false | false |
yingDev/QingDict | QingDict-Result/ResultWindow.swift | 1 | 9494 | //
// ResultWindowControler.swift
// QingDict
//
// Created by Ying on 12/3/15.
// Copyright © 2015 YingDev.com. All rights reserved.
//
import Cocoa
import WebKit
//TODO: refactor some logic to controller
class ResultWindow : NSPanel, WebFrameLoadDelegate
{
@IBOutlet var titlebarAccCtrl: NSTitlebarAccessoryViewController!
@IBOutlet var starPopoverCtrl: StarViewController!
@IBOutlet weak var starBtn: NSButton!
@IBOutlet var animWindow: NSPanel!
@IBOutlet weak var animWindowText: NSTextField!
@IBOutlet weak var webView: WebView!
@IBOutlet weak var indicator: NSProgressIndicator!
var word: String!
var trans: String? = nil
var pron: String? = nil
var shouldAutoStar = false
private var _qingDictStatusItemFrame: NSRect? = nil
deinit
{
NSDistributedNotificationCenter.defaultCenter().removeObserver(self, name: "QingDict:StatusItemFrame", object: nil);
}
var stared: Bool
{
didSet
{
if starBtn != nil
{
starBtn.state = stared ? NSOnState : NSOffState
}
}
}
override init(contentRect: NSRect, styleMask aStyle: Int, backing bufferingType: NSBackingStoreType, `defer` flag: Bool)
{
stared = false
super.init(contentRect: contentRect, styleMask: aStyle, backing: bufferingType, defer:flag)
level = Int(CGWindowLevelForKey(.UtilityWindowLevelKey));
}
override func awakeFromNib()
{
titlebarAccCtrl.layoutAttribute = NSLayoutAttribute.Right;
self.addTitlebarAccessoryViewController(titlebarAccCtrl);
self.contentView!.wantsLayer = true;
self.contentView!.layer?.backgroundColor = CGColorCreateGenericRGB(1, 1,1, 1)
animWindow.contentView?.wantsLayer = true;
animWindow.contentView?.layer?.backgroundColor = CGColorCreateGenericRGB(0, 0, 0, 0.3);
animWindow.contentView?.layer?.cornerRadius = 9.5;
animWindow.backgroundColor = NSColor.clearColor();
animWindow.ignoresMouseEvents = true;
animWindow.level = Int(CGWindowLevelForKey(CGWindowLevelKey.AssistiveTechHighWindowLevelKey));
self.starPopoverCtrl.onConfirmStar = handleConfirmStar
self.starPopoverCtrl.onDeleteStar = handleDeleteStar
indicator.startAnimation(nil)
NSDistributedNotificationCenter.defaultCenter().addObserver(self, selector: #selector(ResultWindow.HandleDistNoti_GotStatusItemFrame(_:)), name: "QingDict:StatusItemFrame", object: nil, suspensionBehavior: NSNotificationSuspensionBehavior.DeliverImmediately)
self.webView.customUserAgent = "Mozilla/5.0 (iPad; CPU OS 9_0 like Mac OS X) AppleWebKit/601.1.16 (KHTML, like Gecko) Version/8.0 Mobile/13A171a Safari/600.1.4";
}
func HandleDistNoti_GotStatusItemFrame(noti: NSNotification)
{
Swift.print("ResultWindow.HandleDistNoti_GotStatusItemFrame")
if let dict = noti.userInfo as? [String: String]
{
if let rectStr = dict["frame"]
{
_qingDictStatusItemFrame = NSRectFromString(rectStr)
Swift.print("HandleDistNoti_GotStatusItemFrame: \(_qingDictStatusItemFrame)")
}
}
}
private func postStarNoti()
{
NSDistributedNotificationCenter.defaultCenter().postNotificationName("QingDict:AddWordEntry", object: "QingDict-Result", userInfo: ["word": self.word, "trans": self.trans ?? ""], deliverImmediately: true)
}
private func handleConfirmStar(sender: StarViewController)
{
self.word = sender.txtWord.stringValue
self.trans = sender.txtTrans.stringValue
self.pron = sender.txtPron.stringValue
animWindowText.stringValue = sender.txtWord.stringValue;
let from = sender.txtWord.window!.convertRectToScreen(sender.txtWord.convertRect(sender.txtWord.bounds, toView: nil));
animWindow.setFrame(NSRect(origin: CGPoint(x:from.origin.x - 4, y:from.origin.y - 1), size: self.animWindowText.frame.size), display: true)
animWindow.orderFront(nil)
stared = true;
performSelector(#selector(ResultWindow.animateAnimWindow), withObject: nil, afterDelay: 0.1);
postStarNoti()
}
private func handleDeleteStar(sender: StarViewController)
{
stared = false;
NSDistributedNotificationCenter.defaultCenter().postNotificationName("QingDict:RemoveWordEntry", object: "QingDict-Result", userInfo: ["word": self.word], deliverImmediately: true)
}
func webView(sender: WebView!, didFinishLoadForFrame frame: WebFrame!)
{
Swift.print("webView didFinishLoadForFrame: \(frame) * \(sender.mainFrame)")
indicator.stopAnimation(nil)
indicator.hidden = true;
starBtn.hidden = false;
//FIXME: youdao.com始终不成立???
//HACK: 用户可能将页面跳转到其他地方。始终尝试提起
//if frame == webView.mainFrame
//if trans == nil
//{
injectJsCss(); //由于有时候mainFrame可能很长时间无法加载完。。。so,无奈允许执行N次
//}
webView.hidden = false;
}
func loadUrl(url: String)
{
webView.mainFrame.loadRequest(NSURLRequest(URL: NSURL(string: url)!));
}
//TODO: customizations
func injectJsCss()
{
//js
//webView.stringByEvaluatingJavaScriptFromString("window.scrollTo(0,120)");
//自动发音
/*webView.stringByEvaluatingJavaScriptFromString("setTimeout(function(){" +
"var prons = document.getElementsByClassName('pronounce');" +
"if(prons.length > 0){ prons[prons.length -1].children[1].click(); }" +
"}, 50)");*/
//提取查询的单词
let word = webView.stringByEvaluatingJavaScriptFromString("document.querySelector('#ec h2 span').innerText.trim()");
if word.characters.count > 0
{
self.word = word
Swift.print("ResultWindow.injectJsCss: extracted word: \(word)")
}else
{
self.word = nil
shouldAutoStar = false
return;
}
//提取释义
let trans = webView.stringByEvaluatingJavaScriptFromString("document.querySelector('#ec ul').innerText.trim()");
if trans.characters.count > 0
{
self.trans = trans
//Swift.print(trans)
}else
{
self.trans = nil
shouldAutoStar = false
return;
}
//提取音标
let pron = webView.stringByEvaluatingJavaScriptFromString("document.querySelector('#ec .phonetic').innerText");
if pron.characters.count > 0
{
self.pron = pron;
}else
{
self.pron = nil
}
if shouldAutoStar
{
postStarNoti()
shouldAutoStar = false
}
//css
let doc = webView.mainFrameDocument;
let styleElem = doc.createElement("style");
styleElem.setAttribute("type", value: "text/css")
let cssText = doc.createTextNode("body{ background:#fff!important; font-family: 'PingFang SC'!important;} #ec>h2>span { font-family:serif; font-weight:100; font-size:24px; padding:0.5em 0 } #ec>h2>div{ font-size:12px !important; color:gray; } #bd{background:white;} #dictNav, .amend{ display:none; }");
styleElem.appendChild(cssText)
let headElem = doc.getElementsByTagName("head").item(0);
headElem.appendChild(styleElem);
}
@IBAction func star(sender: AnyObject)
{
let btn = sender as! NSButton;
if starPopoverCtrl.shown
{
starPopoverCtrl.close();
}
else if self.word != nil
{
//TODO: temp
starPopoverCtrl.txtWord.stringValue = self.word;
starPopoverCtrl.txtTrans.stringValue = self.trans ?? ""
starPopoverCtrl.txtPron.stringValue = self.pron ?? ""
starPopoverCtrl.showRelativeToRect(btn.frame, ofView: btn, preferredEdge: NSRectEdge.MinY);
//查询statusItem的位置
NSDistributedNotificationCenter.defaultCenter().postNotificationName("QingDict:QueryStatusItemFrame", object: "QingDict-Result", userInfo: nil, deliverImmediately: true)
}
btn.state = stared ? NSOnState : NSOffState
}
func animateAnimWindow()
{
if _qingDictStatusItemFrame != nil
{
animWindow.setFrame(_qingDictStatusItemFrame!, display: true, animate: true);
}
animWindow.contentView?.animator().alphaValue = 0
animWindow.performSelector(#selector(NSWindow.orderOut(_:)), withObject: nil, afterDelay: 1);
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override var canBecomeKeyWindow: Bool { return true }
override var canBecomeMainWindow: Bool { return true }
}
class StarViewController : NSViewController, NSTextFieldDelegate
{
@IBOutlet var popOver: NSPopover!
@IBOutlet weak var txtWord: NSTextField!
@IBOutlet weak var txtPron: NSTextField!
@IBOutlet weak var txtTrans: NSTextField!
var onConfirmStar: ((StarViewController)->())? = nil;
var onDeleteStar: ((StarViewController)->())? = nil;
func showRelativeToRect(rect: NSRect, ofView: NSView, preferredEdge: NSRectEdge)
{
popOver.showRelativeToRect(rect, ofView: ofView, preferredEdge: preferredEdge);
}
func close()
{
popOver.close()
}
var shown: Bool
{
return popOver.shown
}
override func viewDidAppear()
{
txtTrans.becomeFirstResponder();
//txtWord.hidden = false;
}
@IBAction func confirmStar(sender: AnyObject)
{
popOver.close();
onConfirmStar?(self);
}
@IBAction func deleteStar(sender: AnyObject)
{
close()
onDeleteStar?(self);
}
func control(control: NSControl, textView: NSTextView, doCommandBySelector commandSelector: Selector) -> Bool
{
var result = false
if commandSelector == #selector(NSResponder.insertNewline(_:))
{
// new line action:
// always insert a line-break character and don’t cause the receiver to end editing
textView.insertNewlineIgnoringFieldEditor(nil)
result = true
}
return result;
}
/*func animateAnimWindow()
{
animWindow.setFrame(NSRect(origin: CGPoint(x:1000, y:900 - animWindow.frame.height), size: animWindow.frame.size), display: true, animate: true);
}*/
}
| gpl-3.0 | bc73ced9858035a778b92c6c914aab5b | 26.78869 | 304 | 0.728178 | 3.547492 | false | false | false | false |
OlegKetrar/NumberPad | Sources/LongPressButton.swift | 1 | 2184 | //
// LongPressButton.swift
// NumberPad
//
// Created by Oleg Ketrar on 30.11.16.
//
//
import UIKit
final class LongPressButton: UIButton {
private var timer: Timer?
private var fireClosure: () -> Void = {}
private let holdDelay: TimeInterval = 0.45
private var timerInterval: TimeInterval = 0.1
private var startTimestamp: TimeInterval?
deinit {
timer?.invalidate()
removeTarget(self, action: #selector(actionHold), for: .touchUpInside)
removeTarget(self, action: #selector(actionRelease), for: .touchUpInside)
removeTarget(self, action: #selector(actionRelease), for: .touchUpOutside)
}
private func invalidateTimer() {
timer?.invalidate()
startTimestamp = nil
}
/// Start hold event recognition after delay.
private func recognizeHoldEvent() -> Bool {
guard let startTimestamp = startTimestamp else { return false }
let timestamp = Date().timeIntervalSinceReferenceDate
return timestamp >= startTimestamp + holdDelay
}
// MARK: Subscribe
func addAction(forContiniusHoldWith interval: TimeInterval, action: @escaping () -> Void) {
// remove old timer
invalidateTimer()
// save
timerInterval = interval
fireClosure = action
// subscribe
addTarget(self, action: #selector(actionHold), for: .touchDown)
addTarget(self, action: #selector(actionRelease), for: .touchUpInside)
addTarget(self, action: #selector(actionRelease), for: .touchUpOutside)
}
// MARK: Actions
/// Fire on touchDown & set timer to catch hold events.
@objc private func actionHold() {
fireClosure()
startTimestamp = Date().timeIntervalSinceReferenceDate
timer = Timer.scheduledTimer(
timeInterval: timerInterval,
target: self,
selector: #selector(actionFire),
userInfo: nil,
repeats: true)
}
@objc private func actionRelease() {
invalidateTimer()
}
@objc private func actionFire() {
guard recognizeHoldEvent() else { return }
fireClosure()
}
}
| mit | ff57b814f66f9b8eb4d48407e8595443 | 27 | 95 | 0.635989 | 4.896861 | false | false | false | false |
willpowell8/LocalizationKit_iOS | Examples/iOS_Swift_Cocoapods/LocalizationKit/AppDelegate.swift | 1 | 3093 | //
// AppDelegate.swift
// LocalizationKit
//
// Created by Will Powell on 11/08/2016.
// Copyright (c) 2016 Will Powell. All rights reserved.
//
import UIKit
import LocalizationKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// DEFINING APP SETTINGS DEFAULTS
var appDefaults = Dictionary<String, AnyObject>()
appDefaults["live_localization"] = true as AnyObject?;
UserDefaults.standard.register(defaults: appDefaults)
UserDefaults.standard.synchronize()
let str = Localization.parse(str:"Name*")
let str2 = Localization.parse(str:"Hello how are you !?>")
print("\(str)")
print("\(str2)")
// LOCALIZATION KIT START DEFINED HERE
Localization.ifEmptyShowKey = true
Localization.start(appKey: "0509b42d-d783-4084-8f91-aeaf0c94595a", useSettings:true)
Localization.availableLanguages { (languages) in
print("Languages");
}
//
// Other options
// Localization.start(appKey: "407f3581-648e-4099-b761-e94136a6628d", live:true) - to run live mode regardless
//
// LOCALIZATION KIT END DEFINED
return true
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
| mit | fa25933a71330abada8412ade9b8b614 | 43.826087 | 285 | 0.70902 | 5.070492 | false | false | false | false |
hanhailong/practice-swift | CoreGraphics/AnimatedBear/AnimatedBear/GameViewController.swift | 3 | 2099 | //
// GameViewController.swift
// AnimatedBear
//
// Created by Domenico Solazzo on 7/30/14.
// Copyright (c) 2014 Domenico Solazzo. All rights reserved.
//
import UIKit
import SpriteKit
extension SKNode {
class func unarchiveFromFile(file : NSString) -> SKNode? {
let path = NSBundle.mainBundle().pathForResource(file, ofType: "sks")
var sceneData = NSData.dataWithContentsOfFile(path, options: .DataReadingMappedIfSafe, error: nil)
var archiver = NSKeyedUnarchiver(forReadingWithData: sceneData)
archiver.setClass(self.classForKeyedUnarchiver(), forClassName: "SKScene")
let scene = archiver.decodeObjectForKey(NSKeyedArchiveRootObjectKey) as GameScene
archiver.finishDecoding()
return scene
}
}
class GameViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
if let scene = GameScene.unarchiveFromFile("GameScene") as? GameScene {
// Configure the view.
let skView = self.view as SKView
skView.showsFPS = true
skView.showsNodeCount = true
/* Sprite Kit applies additional optimizations to improve rendering performance */
skView.ignoresSiblingOrder = true
/* Set the scale mode to scale to fit the window */
scene.scaleMode = .AspectFill
skView.presentScene(scene)
}
}
override func shouldAutorotate() -> Bool {
return true
}
override func supportedInterfaceOrientations() -> Int {
if UIDevice.currentDevice().userInterfaceIdiom == .Phone {
return Int(UIInterfaceOrientationMask.AllButUpsideDown.toRaw())
} else {
return Int(UIInterfaceOrientationMask.All.toRaw())
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Release any cached data, images, etc that aren't in use.
}
override func prefersStatusBarHidden() -> Bool {
return true
}
}
| mit | 932cbef7c60765069176bc0fa418b19f | 29.867647 | 106 | 0.638876 | 5.627346 | false | false | false | false |
loudnate/LoopKit | LoopKitUI/Views/AuthenticationTableViewCell.swift | 1 | 3571 | //
// AuthenticationTableViewCell.swift
// Loop
//
// Created by Nate Racklyeft on 7/2/16.
// Copyright © 2016 Nathan Racklyeft. All rights reserved.
//
import UIKit
final class AuthenticationTableViewCell: UITableViewCell {
@IBOutlet weak var titleLabel: UILabel!
@IBOutlet weak var textField: UITextField!
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
if selected {
textField.becomeFirstResponder()
}
}
override func prepareForReuse() {
super.prepareForReuse()
textField.delegate = nil
credentialOptionPicker = nil
}
var credentialOptionPicker: CredentialOptionPicker? {
didSet {
if let picker = credentialOptionPicker {
picker.delegate = self
textField.text = picker.selectedOption.title
textField.inputView = picker.view
textField.tintColor = .clear // Makes the cursor invisible
} else {
textField.inputView = nil
textField.tintColor = nil
}
}
}
var value: String? {
if let picker = credentialOptionPicker {
return picker.value
} else {
return textField.text
}
}
}
extension AuthenticationTableViewCell: CredentialOptionPickerDelegate {
func credentialOptionDataSourceDidUpdateValue(_ picker: CredentialOptionPicker) {
textField.text = picker.selectedOption.title
textField.delegate?.textFieldDidEndEditing?(textField)
}
}
protocol CredentialOptionPickerDelegate: class {
func credentialOptionDataSourceDidUpdateValue(_ picker: CredentialOptionPicker)
}
class CredentialOptionPicker: NSObject, UIPickerViewDataSource, UIPickerViewDelegate {
let options: [(title: String, value: String)]
weak var delegate: CredentialOptionPickerDelegate?
let view = UIPickerView()
var selectedOption: (title: String, value: String) {
let index = view.selectedRow(inComponent: 0)
guard index >= options.startIndex && index < options.endIndex else {
return options[0]
}
return options[index]
}
var value: String? {
get {
return selectedOption.value
}
set {
let index: Int
if let value = newValue, let optionIndex = options.firstIndex(where: { $0.value == value }) {
index = optionIndex
} else {
index = 0
}
view.selectRow(index, inComponent: 0, animated: view.superview != nil)
}
}
init(options: [(title: String, value: String)]) {
assert(options.count > 0, "At least one option must be specified")
self.options = options
super.init()
view.dataSource = self
view.delegate = self
}
// MARK: - UIPickerViewDataSource
func numberOfComponents(in pickerView: UIPickerView) -> Int {
return 1
}
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
return options.count
}
// MARK: - UIPickerViewDelegate
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
return options[row].title
}
func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
delegate?.credentialOptionDataSourceDidUpdateValue(self)
}
}
| mit | c5857ba7998bbd96865436ffe69e75f7 | 25.842105 | 111 | 0.630532 | 5.15896 | false | false | false | false |
MichaelSelsky/TheBeatingAtTheGates | Carthage/Checkouts/VirtualGameController/Samples/SceneKitDemo/SceneKitDemo/SharedCode.swift | 1 | 10874 | //
// SharedCode.swift
// SceneKitDemo
//
// Created by Rob Reuss on 12/8/15.
// Copyright © 2015 Rob Reuss. All rights reserved.
//
import Foundation
import SceneKit
import VirtualGameController
class SharedCode: NSObject, SCNSceneRendererDelegate {
var ship: SCNNode!
var lightNode: SCNNode!
var cameraNode: SCNNode!
func setup(ship: SCNNode, lightNode: SCNNode, cameraNode: SCNNode) {
self.ship = ship
self.lightNode = lightNode
self.cameraNode = cameraNode
NSNotificationCenter.defaultCenter().addObserver(self, selector: "controllerDidConnect:", name: VgcControllerDidConnectNotification, object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: "controllerDidDisconnect:", name: VgcControllerDidDisconnectNotification, object: nil)
}
func scaleShipByValue(var scaleValue: CGFloat) {
scaleValue = scaleValue + 1
if scaleValue < 0.10 { scaleValue = 0.10 }
ship.runAction(SCNAction.scaleTo(scaleValue, duration: 1.0))
}
/* IMPLEMENTATION USING RENDER LOOP
func renderer(renderer: SCNSceneRenderer, willRenderScene scene: SCNScene, atTime time: NSTimeInterval) {
}
func renderer(renderer: SCNSceneRenderer, didApplyAnimationsAtTime time: NSTimeInterval) {
}
func renderer(renderer: SCNSceneRenderer, didRenderScene scene: SCNScene, atTime time: NSTimeInterval) {
}
func renderer(renderer: SCNSceneRenderer, didSimulatePhysicsAtTime time: NSTimeInterval) {
}
func renderer(renderer: SCNSceneRenderer, updateAtTime time: NSTimeInterval) {
if VgcController.controllers().count > 0 {
let controller = VgcController.controllers()[0]
let input = controller.motion!
let amplify = 2.0
let x = -(input.attitude.x) * amplify
let y = -(input.attitude.z) * amplify
let z = -(input.attitude.y) * amplify
ship.runAction(SCNAction.repeatAction(SCNAction.rotateToX(CGFloat(x), y: CGFloat(y), z: CGFloat(z), duration: 0.03), count: 1))
ship.runAction(SCNAction.moveTo(SCNVector3.init(CGFloat( ship.position.x), CGFloat(-(input.gravity.y * 6.0)), CGFloat( ship.position.z)), duration: 1.0))
}
}
*/
@objc func controllerDidConnect(notification: NSNotification) {
// If we're enhancing a hardware controller, we should display the Peripheral UI
// instead of the debug view UI
if VgcManager.appRole == .EnhancementBridge { return }
guard let newController: VgcController = notification.object as? VgcController else {
vgcLogDebug("Got nil controller in controllerDidConnect")
return
}
if newController.isHardwareController { return }
if newController.deviceInfo.controllerType == .MFiHardware { return }
VgcManager.peripheralSetup = VgcPeripheralSetup()
// Turn on motion to demonstrate that
VgcManager.peripheralSetup.motionActive = false
VgcManager.peripheralSetup.enableMotionAttitude = true
VgcManager.peripheralSetup.enableMotionGravity = true
VgcManager.peripheralSetup.enableMotionUserAcceleration = false
VgcManager.peripheralSetup.enableMotionRotationRate = false
VgcManager.peripheralSetup.sendToController(newController)
// Dpad adjusts lighting position
#if os(iOS) || os(tvOS)
newController.extendedGamepad?.dpad.valueChangedHandler = { (dpad, xValue, yValue) in
self.lightNode.position = SCNVector3(x: Float(xValue * 10), y: Float(yValue * 20), z: Float(yValue * 30) + 10)
}
#endif
#if os(OSX)
newController.extendedGamepad?.dpad.valueChangedHandler = { (dpad, xValue, yValue) in
self.lightNode.position = SCNVector3(x: CGFloat(xValue * 10), y: CGFloat(yValue * 20), z: CGFloat(yValue * 30) + 10)
}
#endif
// Left thumbstick controls move the plane left/right and up/down
newController.extendedGamepad?.leftThumbstick.valueChangedHandler = { (dpad, xValue, yValue) in
self.ship.runAction(SCNAction.moveTo(SCNVector3.init(xValue * 5, yValue * 5, 0.0), duration: 0.3))
}
// Right thumbstick Y axis controls plane scale
newController.extendedGamepad?.rightThumbstick.yAxis.valueChangedHandler = { (input, value) in
self.scaleShipByValue(CGFloat((newController.extendedGamepad?.rightThumbstick.yAxis.value)!))
}
// Right Shoulder pushes the ship away from the user
newController.extendedGamepad?.rightShoulder.valueChangedHandler = { (input, value, pressed) in
self.scaleShipByValue(CGFloat((newController.extendedGamepad?.rightShoulder.value)!))
}
// Left Shoulder resets the reference frame
newController.extendedGamepad?.leftShoulder.valueChangedHandler = { (input, value, pressed) in
self.ship.runAction(SCNAction.repeatAction(SCNAction.rotateToX(0, y: 0, z: 0, duration: 10.0), count: 1))
}
// Right trigger draws the plane toward the user
newController.extendedGamepad?.rightTrigger.valueChangedHandler = { (input, value, pressed) in
self.scaleShipByValue(-(CGFloat((newController.extendedGamepad?.rightTrigger.value)!)))
}
newController.elements.image.valueChangedHandler = { (controller, element) in
//vgcLogDebug("Custom element handler fired for Send Image: \(element.value)")
#if os(OSX)
let image = NSImage(data: element.value as! NSData)
#endif
#if os(iOS) || os(tvOS)
let image = UIImage(data: element.value as! NSData)
#endif
// get its material
let material = self.ship.childNodeWithName("shipMesh", recursively: true)!.geometry?.firstMaterial!
/*
// highlight it
SCNTransaction.begin()
SCNTransaction.setAnimationDuration(0.5)
// on completion - unhighlight
SCNTransaction.setCompletionBlock {
SCNTransaction.begin()
SCNTransaction.setAnimationDuration(0.5)
#if os(OSX)
material!.emission.contents = NSColor.blackColor()
#endif
#if os(iOS) || os(tvOS)
material!.emission.contents = UIColor.blackColor()
#endif
SCNTransaction.commit()
}
*/
material!.diffuse.contents = image
//SCNTransaction.commit()
}
// Position ship at a solid origin
ship.runAction(SCNAction.repeatAction(SCNAction.rotateToX(0, y: 0, z: 0, duration: 1.3), count: 1))
// Refresh on all motion changes
newController.motion?.valueChangedHandler = { (input: VgcMotion) in
let amplify = 3.14158
// Invert these because we want to be able to have the ship display in a way
// that mirrors the position of the iOS device
let x = -(input.attitude.x) * amplify
let y = -(input.attitude.z) * amplify
let z = -(input.attitude.y) * amplify
self.ship.runAction(SCNAction.repeatAction(SCNAction.rotateToX(CGFloat(x), y: CGFloat(y), z: CGFloat(z), duration: 0.15), count: 1))
//ship.runAction(SCNAction.moveTo(SCNVector3.init(CGFloat(x) * 4.0, CGFloat(y) * 4.0, CGFloat(z) * 4.0), duration: 0.3))
// The following will give the ship a bit of "float" that relates to the up/down motion of the iOS device.
// Disable the following if you want to focus on using the on-screen device input controls instead of motion input.
// If this section is not disabled, and you use the onscreen input controls, the two will "fight" over control
// and create hurky jerky motion.
/*
var xValue = CGFloat(input.gravity.x)
var yValue = CGFloat(input.userAcceleration.y)
xValue = xValue + (xValue * 3.0)
yValue = yValue - (yValue * 20.0)
ship.runAction(SCNAction.moveTo(SCNVector3.init(xValue, yValue, CGFloat( ship.position.z)), duration: 1.6))
*/
}
/*
// Refresh on all motion changes
controller.motion?.valueChangedHandler = { (input: VgcMotion) in
let amplify = 2.75
// Invert these because we want to be able to have the ship display in a way
// that mirrors the position of the iOS device
let x = -(input.attitude.x) * amplify
let y = -(input.attitude.z) * amplify
let z = -(input.attitude.y) * amplify
ship.runAction(SCNAction.repeatAction(SCNAction.rotateToX(CGFloat(x), y: CGFloat(y), z: CGFloat(z), duration: 0.15), count: 1))
//ship.runAction(SCNAction.moveTo(SCNVector3.init(CGFloat(x) * 4.0, CGFloat(y) * 4.0, CGFloat(z) * 4.0), duration: 0.3))
// The following will give the ship a bit of "float" that relates to the up/down motion of the iOS device.
// Disable the following if you want to focus on using the on-screen device input controls instead of motion input.
// If this section is not disabled, and you use the onscreen input controls, the two will "fight" over control
// and create hurky jerky motion.
/*
var xValue = CGFloat(input.gravity.x)
var yValue = CGFloat(input.userAcceleration.y)
xValue = xValue + (xValue * 3.0)
yValue = yValue - (yValue * 20.0)
ship.runAction(SCNAction.moveTo(SCNVector3.init(xValue, yValue, CGFloat( ship.position.z)), duration: 1.6))
*/
}
*/
}
@objc func controllerDidDisconnect(notification: NSNotification) {
//guard let controller: VgcController = notification.object as? VgcController else { return }
ship.runAction(SCNAction.repeatAction(SCNAction.rotateToX(0, y: 0, z: 0, duration: 1.0), count: 1))
}
}
| mit | e3ecdc8cfffe437067b86c32a54ef42c | 39.722846 | 165 | 0.59634 | 4.830298 | false | false | false | false |
CosmicMind/MaterialKit | Sources/iOS/FABMenuController.swift | 1 | 5861 | /*
* Copyright (C) 2015 - 2018, Daniel Dahan and CosmicMind, Inc. <http://cosmicmind.com>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* * Neither the name of CosmicMind nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
import UIKit
public enum FABMenuBacking {
case none
case fade
case blur
}
extension UIViewController {
/**
A convenience property that provides access to the FABMenuController.
This is the recommended method of accessing the FABMenuController
through child UIViewControllers.
*/
public var fabMenuController: FABMenuController? {
return traverseViewControllerHierarchyForClassType()
}
}
open class FABMenuController: TransitionController {
/// Reference to the MenuView.
@IBInspectable
open var fabMenu = FABMenu()
/// A FABMenuBacking value type.
open var fabMenuBacking = FABMenuBacking.blur
/// The fabMenuBacking UIBlurEffectStyle.
open var fabMenuBackingBlurEffectStyle = UIBlurEffectStyle.light
/// A reference to the blurView.
open fileprivate(set) var blurView: UIView?
open override func layoutSubviews() {
super.layoutSubviews()
rootViewController.view.frame = view.bounds
}
open override func prepare() {
super.prepare()
prepareFABMenu()
}
}
extension FABMenuController: FABMenuDelegate {}
fileprivate extension FABMenuController {
/// Prepares the fabMenu.
func prepareFABMenu() {
fabMenu.delegate = self
fabMenu.layer.zPosition = 1000
fabMenu.handleFABButtonCallback = { [weak self] in
self?.handleFABButtonCallback(button: $0)
}
fabMenu.handleOpenCallback = { [weak self] in
self?.handleOpenCallback()
}
fabMenu.handleCloseCallback = { [weak self] in
self?.handleCloseCallback()
}
fabMenu.handleCompletionCallback = { [weak self] in
self?.handleCompletionCallback(view: $0)
}
view.addSubview(fabMenu)
}
}
fileprivate extension FABMenuController {
/// Shows the fabMenuBacking.
func showFabMenuBacking() {
showFade()
showBlurView()
}
/// Hides the fabMenuBacking.
func hideFabMenuBacking() {
hideFade()
hideBlurView()
}
/// Shows the blurView.
func showBlurView() {
guard .blur == fabMenuBacking else {
return
}
guard !fabMenu.isOpened, fabMenu.isEnabled else {
return
}
guard nil == blurView else {
return
}
let blur = UIVisualEffectView(effect: UIBlurEffect(style: fabMenuBackingBlurEffectStyle))
blurView = UIView()
blurView?.layout(blur).edges()
view.layout(blurView!).edges()
view.bringSubview(toFront: fabMenu)
}
/// Hides the blurView.
func hideBlurView() {
guard .blur == fabMenuBacking else {
return
}
guard fabMenu.isOpened, fabMenu.isEnabled else {
return
}
blurView?.removeFromSuperview()
blurView = nil
}
/// Shows the fade.
func showFade() {
guard .fade == fabMenuBacking else {
return
}
guard !fabMenu.isOpened, fabMenu.isEnabled else {
return
}
UIView.animate(withDuration: 0.15, animations: { [weak self] in
self?.rootViewController.view.alpha = 0.15
})
}
/// Hides the fade.
func hideFade() {
guard .fade == fabMenuBacking else {
return
}
guard fabMenu.isOpened, fabMenu.isEnabled else {
return
}
UIView.animate(withDuration: 0.15, animations: { [weak self] in
self?.rootViewController.view.alpha = 1
})
}
}
fileprivate extension FABMenuController {
/**
Handler to toggle the FABMenu opened or closed.
- Parameter button: A UIButton.
*/
func handleFABButtonCallback(button: UIButton) {
guard fabMenu.isOpened else {
fabMenu.open(isTriggeredByUserInteraction: true)
return
}
fabMenu.close(isTriggeredByUserInteraction: true)
}
/// Handler for when the FABMenu.open function is called.
func handleOpenCallback() {
isUserInteractionEnabled = false
showFabMenuBacking()
}
/// Handler for when the FABMenu.close function is called.
func handleCloseCallback() {
isUserInteractionEnabled = false
hideFabMenuBacking()
}
/**
Completion handler for FABMenu open and close calls.
- Parameter view: A UIView.
*/
func handleCompletionCallback(view: UIView) {
if view == fabMenu.fabMenuItems.last {
isUserInteractionEnabled = true
}
}
}
| bsd-3-clause | 6fd9138884a87992c352c7eff03d7c2e | 26.009217 | 93 | 0.696809 | 4.491188 | false | false | false | false |
dyzdyz010/ChineseBorderPoliceNews | BorderPoliceNews/BorderPoliceNews/EntryViewController.swift | 1 | 3634 | //
// EntryViewController.swift
// FrontierPoliceNews
//
// Created by Du Yizhuo on 16/2/26.
// Copyright © 2016年 MLTT. All rights reserved.
//
import UIKit
import YYText
import YYWebImage
class EntryViewController: UIViewController {
@IBOutlet weak var titleLabel: YYLabel!
@IBOutlet weak var authorLabel: YYLabel!
@IBOutlet weak var upperSubtitleLabel: UILabel!
@IBOutlet weak var lowerSubtitleLabel: UILabel!
@IBOutlet weak var imageView: UIImageView!
@IBOutlet weak var imageViewHeightConstraint: NSLayoutConstraint!
@IBOutlet weak var contentLabel: YYLabel!
@IBOutlet weak var loadingAnimator: UIActivityIndicatorView!
var entry: Entry? = nil
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
self.navigationItem.title = "文章详情"
if entry?.author == "载入中" {
entry?.reload(){
self.makeContent()
}
} else {
makeContent()
}
}
func setTitles() {
self.titleLabel.text = self.entry?.title
self.authorLabel.text = self.entry?.author
self.upperSubtitleLabel.text = entry?.subtitles[0]
self.lowerSubtitleLabel.text = entry?.subtitles[1]
// self.upperSubtitleLabel.hidden = true
self.loadingAnimator.hidden = true
}
func makeContent() {
setTitles()
if entry?.image == nil {
self.imageViewHeightConstraint.constant = 0
}
// let imgpath = NSBundle.mainBundle().pathForResource("logo", ofType: "png")
// self.imageView.image = UIImage(contentsOfFile: imgpath!)
self.imageView.yy_setImageWithURL(entry?.image, placeholder: nil, options: YYWebImageOptions.ProgressiveBlur) { (img, url, from, stage, err) -> Void in
if err != nil {
print(err)
}
}
let font = UIFont(name: "PingFangSC-Light", size: 18)!
let text = NSMutableAttributedString(string: "")
for p in (entry?.text)! {
let paragraph = NSMutableAttributedString(string: p)
text.appendAttributedString(paragraph)
}
text.yy_font = font
text.yy_firstLineHeadIndent = 38
text.yy_paragraphSpacing = 10
self.contentLabel.attributedText = text
}
@IBAction func shareButtonClicked(sender: AnyObject) {
UMSocialData.defaultData().extConfig.wechatSessionData.url = self.entry?.link
UMSocialData.defaultData().extConfig.wechatTimelineData.url = self.entry?.link
var img = self.imageView.image
if img == nil {
img = UIImage(named: "Link")
}
UMSocialSnsService.presentSnsIconSheetView(self, appKey: "5704bcbc67e58e9b3500150f", shareText: self.titleLabel.text, shareImage: img, shareToSnsNames: [UMShareToWechatSession, UMShareToWechatTimeline], delegate: nil)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| mit | e680ad50fa3bf0a9a69f1fde489f83cb | 31.585586 | 225 | 0.625657 | 4.829105 | false | false | false | false |
abaca100/Nest | iOS-NestDK/CharacteristicCell.swift | 1 | 6930 | /*
Copyright (C) 2015 Apple Inc. All Rights Reserved.
See LICENSE.txt for this sample’s licensing information
Abstract:
`CharacteristicCell` is a superclass which represents the state of a HomeKit characteristic.
*/
import UIKit
import HomeKit
/// Methods for handling cell reads and updates.
protocol CharacteristicCellDelegate {
/**
Called whenever the control within the cell updates its value.
- parameter cell: The cell which has updated its value.
- parameter newValue: The new value represented by the cell's control.
- parameter characteristic: The characteristic the cell represents.
- parameter immediate: Whether or not to update external values immediately.
For example, Slider cells should not update immediately upon value change,
so their values are cached and updates are coalesced. Subclasses can decide
whether or not their values are meant to be updated immediately.
*/
func characteristicCell(cell: CharacteristicCell, didUpdateValue value: AnyObject, forCharacteristic characteristic: HMCharacteristic, immediate: Bool)
/**
Called when the characteristic cell needs to reload its value from an external source.
Consider using this call to look up values in memory or query them from an accessory.
- parameter cell: The cell requesting a value update.
- parameter characteristic: The characteristic for whose value the cell is asking.
- parameter completion: The closure that the cell provides to be called when values have been read successfully.
*/
func characteristicCell(cell: CharacteristicCell, readInitialValueForCharacteristic characteristic: HMCharacteristic, completion: (AnyObject?, NSError?) -> Void)
}
/**
A `UITableViewCell` subclass that displays the current value of an `HMCharacteristic` and
notifies its delegate of changes. Subclasses of this class will provide additional controls
to display different kinds of data.
*/
class CharacteristicCell: UITableViewCell {
/// An alpha percentage used when disabling cells.
static let DisabledAlpha: CGFloat = 0.4
/// Required init.
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
/// Subclasses can return false if they have many frequent updates that should be deferred.
class var updatesImmediately: Bool {
return true
}
// MARK: Properties
@IBOutlet weak var typeLabel: UILabel!
@IBOutlet weak var valueLabel: UILabel!
@IBOutlet weak var favoriteButton: UIButton!
@IBOutlet weak var favoriteButtonWidthConstraint: NSLayoutConstraint!
@IBOutlet weak var favoriteButtonHeightContraint: NSLayoutConstraint!
/**
Show / hide the favoriteButton and adjust the constraints
to ensure proper layout.
*/
var showsFavorites = false {
didSet {
if showsFavorites {
favoriteButton.hidden = false
favoriteButtonWidthConstraint.constant = favoriteButtonHeightContraint.constant
}
else {
favoriteButton.hidden = true
favoriteButtonWidthConstraint.constant = 15.0
}
}
}
/**
- returns: `true` if the represented characteristic is reachable;
`false` otherwise.
*/
var enabled: Bool {
return (characteristic.service?.accessory?.reachable ?? false)
}
/**
The value currently represented by the cell.
This is not necessarily the value of this cell's characteristic,
because the cell's value changes independently of the characteristic.
*/
var value: AnyObject?
/// The delegate that will respond to cell value changes.
var delegate: CharacteristicCellDelegate?
/**
The characteristic represented by this cell.
When this is set, the cell populates based on
the characteristic's value and requests an initial value
from its delegate.
*/
var characteristic: HMCharacteristic! {
didSet {
typeLabel.text = characteristic.localizedCharacteristicType
selectionStyle = characteristic.isIdentify ? .Default : .None
setValue(characteristic.value, notify: false)
if characteristic.isWriteOnly {
// Don't read the value for write-only characteristics.
return
}
// Set initial state of the favorite button
//favoriteButton.selected = characteristic.isFavorite
// "Enable" the cell if the accessory is reachable or we are displaying the favorites.
// Configure the views.
typeLabel.alpha = enabled ? 1.0 : CharacteristicCell.DisabledAlpha
valueLabel?.alpha = enabled ? 1.0 : CharacteristicCell.DisabledAlpha
if enabled {
delegate?.characteristicCell(self, readInitialValueForCharacteristic: characteristic) { value, error in
if let error = error {
print("HomeKit: Error reading value for characteristic \(self.characteristic): \(error.localizedDescription).")
}
else {
self.setValue(value, notify: false)
}
}
}
}
}
/// Resets the value label to the localized description from HMCharacteristic+Readability.
func resetValueLabel() {
if let value = value {
valueLabel?.text = characteristic.localizedDescriptionForValue(value)
}
}
/**
Toggles the star button and saves the favorite status
of the characteristic in the FavoriteManager.
*/
@IBAction func didTapFavoriteButton(sender: UIButton) {
sender.selected = !sender.selected
//characteristic.isFavorite = sender.selected
}
/**
Sets the cell's value and resets the label.
- parameter newValue: The new value.
- parameter notify: If true, the cell notifies its delegate of the change.
*/
func setValue(newValue: AnyObject?, notify: Bool) {
value = newValue
if let newValue = newValue {
resetValueLabel()
/*
We do not allow the setting of nil values from the app,
but we do have to deal with incoming nil values.
*/
if notify {
delegate?.characteristicCell(self, didUpdateValue: newValue, forCharacteristic: characteristic, immediate: self.dynamicType.updatesImmediately)
}
}
}
}
| apache-2.0 | 317bae77381b45c75530524597dcfa3c | 37.065934 | 165 | 0.631928 | 5.787803 | false | false | false | false |
buyiyang/iosstar | iOSStar/Model/MarketModel/MarketRequestModel.swift | 3 | 2126 | //
// MarketRequestModel.swift
// iOSStar
//
// Created by J-bb on 17/5/31.
// Copyright © 2017年 YunDian. All rights reserved.
//
import Foundation
class MarketBaseModel: BaseModel {
var id:Int64 = StarUserModel.getCurrentUser()?.userinfo?.id ?? 0
var token = StarUserModel.getCurrentUser()?.token ?? ""
}
class RealTimeRequestModel:MarketBaseModel {
var symbolInfos = [SymbolInfo]()
}
class SymbolInfo: BaseModel {
var symbol = ""
var aType = 5
}
class TimeLineRequestModel: MarketBaseModel {
var symbol = ""
var aType = 5
}
class StarListRequestModel: MarketBaseModel {
var sort = 0
var aType:Int32 = 5
var start:Int32 = 0
var count:Int32 = 20
}
class SendCommentModel: BaseModel {
var symbol = ""
var fans_id = "\(StarUserModel.getCurrentUser()?.userinfo?.id ?? 0)"
var nick_name = StarUserModel.getCurrentUser()?.userinfo?.agentName ?? ""
var comments = ""
var head_url = StarUserModel.getCurrentUser()?.userinfo?.avatar_Large ?? ""
}
class CommentListRequestModel: BaseModel {
var symbol = ""
var token = StarUserModel.getCurrentUser()?.token ?? ""
var startPos = 0
var count = 10
}
class MarketSearhModel: MarketBaseModel {
var message = ""
}
class AuctionStatusRequestModel: MarketBaseModel {
var symbol = ""
}
class FanListRequestModel: MarketBaseModel {
var symbol = ""
var buySell:Int32 = 1
var start:Int32 = 0
var star_code = ""
var count:Int64 = 10
}
class PositionCountRequestModel: BaseModel {
var uid:Int64 = StarUserModel.getCurrentUser()?.userinfo?.id ?? 0
var starcode = ""
}
class BuySellPercentRequest: MarketBaseModel {
var symbol = ""
}
class EntrustCountRequestModel: MarketBaseModel {
var symbol = ""
}
class BankCardListRequestModel: MarketBaseModel {
var cardNo = ""
}
class UnbindCardListRequestModel: MarketBaseModel {
var cardNo = ""
}
class BindCardListRequestModel: MarketBaseModel {
var symbol = ""
var account = ""
var bankUsername = ""
var prov = ""
var city = ""
}
| gpl-3.0 | d570423d4c193f258dfbed8b1eca996a | 19.61165 | 79 | 0.658031 | 3.998117 | false | false | false | false |
greenaddress/WalletCordova | plugins-src/cordova-plugin-greenaddress/touchid/Keychain.swift | 4 | 114993 | //
// Keychain.swift
// KeychainAccess
//
// Created by kishikawa katsumi on 2014/12/24.
// Copyright (c) 2014 kishikawa katsumi. 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
import Security
public let KeychainAccessErrorDomain = "com.kishikawakatsumi.KeychainAccess.error"
public enum ItemClass {
case genericPassword
case internetPassword
}
public enum ProtocolType {
case ftp
case ftpAccount
case http
case irc
case nntp
case pop3
case smtp
case socks
case imap
case ldap
case appleTalk
case afp
case telnet
case ssh
case ftps
case https
case httpProxy
case httpsProxy
case ftpProxy
case smb
case rtsp
case rtspProxy
case daap
case eppc
case ipp
case nntps
case ldaps
case telnetS
case imaps
case ircs
case pop3S
}
public enum AuthenticationType {
case ntlm
case msn
case dpa
case rpa
case httpBasic
case httpDigest
case htmlForm
case `default`
}
public enum Accessibility {
/**
Item data can only be accessed
while the device is unlocked. This is recommended for items that only
need be accesible while the application is in the foreground. Items
with this attribute will migrate to a new device when using encrypted
backups.
*/
case whenUnlocked
/**
Item data can only be
accessed once the device has been unlocked after a restart. This is
recommended for items that need to be accesible by background
applications. Items with this attribute will migrate to a new device
when using encrypted backups.
*/
case afterFirstUnlock
/**
Item data can always be accessed
regardless of the lock state of the device. This is not recommended
for anything except system use. Items with this attribute will migrate
to a new device when using encrypted backups.
*/
case always
/**
Item data can
only be accessed while the device is unlocked. This class is only
available if a passcode is set on the device. This is recommended for
items that only need to be accessible while the application is in the
foreground. Items with this attribute will never migrate to a new
device, so after a backup is restored to a new device, these items
will be missing. No items can be stored in this class on devices
without a passcode. Disabling the device passcode will cause all
items in this class to be deleted.
*/
@available(iOS 8.0, OSX 10.10, *)
case whenPasscodeSetThisDeviceOnly
/**
Item data can only
be accessed while the device is unlocked. This is recommended for items
that only need be accesible while the application is in the foreground.
Items with this attribute will never migrate to a new device, so after
a backup is restored to a new device, these items will be missing.
*/
case whenUnlockedThisDeviceOnly
/**
Item data can
only be accessed once the device has been unlocked after a restart.
This is recommended for items that need to be accessible by background
applications. Items with this attribute will never migrate to a new
device, so after a backup is restored to a new device these items will
be missing.
*/
case afterFirstUnlockThisDeviceOnly
/**
Item data can always
be accessed regardless of the lock state of the device. This option
is not recommended for anything except system use. Items with this
attribute will never migrate to a new device, so after a backup is
restored to a new device, these items will be missing.
*/
case alwaysThisDeviceOnly
}
public struct AuthenticationPolicy: OptionSet {
/**
User presence policy using Touch ID or Passcode. Touch ID does not
have to be available or enrolled. Item is still accessible by Touch ID
even if fingers are added or removed.
*/
@available(iOS 8.0, OSX 10.10, *)
@available(watchOS, unavailable)
public static let userPresence = AuthenticationPolicy(rawValue: 1 << 0)
/**
Constraint: Touch ID (any finger). Touch ID must be available and
at least one finger must be enrolled. Item is still accessible by
Touch ID even if fingers are added or removed.
*/
@available(iOS 9.0, *)
@available(OSX, unavailable)
@available(watchOS, unavailable)
public static let touchIDAny = AuthenticationPolicy(rawValue: 1 << 1)
/**
Constraint: Touch ID from the set of currently enrolled fingers.
Touch ID must be available and at least one finger must be enrolled.
When fingers are added or removed, the item is invalidated.
*/
@available(iOS 9.0, *)
@available(OSX, unavailable)
@available(watchOS, unavailable)
public static let touchIDCurrentSet = AuthenticationPolicy(rawValue: 1 << 3)
/**
Constraint: Device passcode
*/
@available(iOS 9.0, OSX 10.11, *)
@available(watchOS, unavailable)
public static let devicePasscode = AuthenticationPolicy(rawValue: 1 << 4)
/**
Constraint logic operation: when using more than one constraint,
at least one of them must be satisfied.
*/
@available(iOS 9.0, *)
@available(OSX, unavailable)
@available(watchOS, unavailable)
public static let or = AuthenticationPolicy(rawValue: 1 << 14)
/**
Constraint logic operation: when using more than one constraint,
all must be satisfied.
*/
@available(iOS 9.0, *)
@available(OSX, unavailable)
@available(watchOS, unavailable)
public static let and = AuthenticationPolicy(rawValue: 1 << 15)
/**
Create access control for private key operations (i.e. sign operation)
*/
@available(iOS 9.0, *)
@available(OSX, unavailable)
@available(watchOS, unavailable)
public static let privateKeyUsage = AuthenticationPolicy(rawValue: 1 << 30)
/**
Security: Application provided password for data encryption key generation.
This is not a constraint but additional item encryption mechanism.
*/
@available(iOS 9.0, *)
@available(OSX, unavailable)
@available(watchOS, unavailable)
public static let applicationPassword = AuthenticationPolicy(rawValue: 1 << 31)
#if swift(>=2.3)
public let rawValue: UInt
public init(rawValue: UInt) {
self.rawValue = rawValue
}
#else
public let rawValue: Int
public init(rawValue: Int) {
self.rawValue = rawValue
}
#endif
}
public struct Attributes {
public var `class`: String? {
return attributes[Class] as? String
}
public var data: Data? {
return attributes[ValueData] as? Data
}
public var ref: Data? {
return attributes[ValueRef] as? Data
}
public var persistentRef: Data? {
return attributes[ValuePersistentRef] as? Data
}
public var accessible: String? {
return attributes[AttributeAccessible] as? String
}
public var accessControl: SecAccessControl? {
if #available(OSX 10.10, *) {
if let accessControl = attributes[AttributeAccessControl] {
return (accessControl as! SecAccessControl)
}
return nil
} else {
return nil
}
}
public var accessGroup: String? {
return attributes[AttributeAccessGroup] as? String
}
public var synchronizable: Bool? {
return attributes[AttributeSynchronizable] as? Bool
}
public var creationDate: Date? {
return attributes[AttributeCreationDate] as? Date
}
public var modificationDate: Date? {
return attributes[AttributeModificationDate] as? Date
}
public var attributeDescription: String? {
return attributes[AttributeDescription] as? String
}
public var comment: String? {
return attributes[AttributeComment] as? String
}
public var creator: String? {
return attributes[AttributeCreator] as? String
}
public var type: String? {
return attributes[AttributeType] as? String
}
public var label: String? {
return attributes[AttributeLabel] as? String
}
public var isInvisible: Bool? {
return attributes[AttributeIsInvisible] as? Bool
}
public var isNegative: Bool? {
return attributes[AttributeIsNegative] as? Bool
}
public var account: String? {
return attributes[AttributeAccount] as? String
}
public var service: String? {
return attributes[AttributeService] as? String
}
public var generic: Data? {
return attributes[AttributeGeneric] as? Data
}
public var securityDomain: String? {
return attributes[AttributeSecurityDomain] as? String
}
public var server: String? {
return attributes[AttributeServer] as? String
}
public var `protocol`: String? {
return attributes[AttributeProtocol] as? String
}
public var authenticationType: String? {
return attributes[AttributeAuthenticationType] as? String
}
public var port: Int? {
return attributes[AttributePort] as? Int
}
public var path: String? {
return attributes[AttributePath] as? String
}
fileprivate let attributes: [String: Any]
init(attributes: [String: Any]) {
self.attributes = attributes
}
public subscript(key: String) -> Any? {
get {
return attributes[key]
}
}
}
public final class Keychain {
public var itemClass: ItemClass {
return options.itemClass
}
public var service: String {
return options.service
}
public var accessGroup: String? {
return options.accessGroup
}
public var server: URL {
return options.server
}
public var protocolType: ProtocolType {
return options.protocolType
}
public var authenticationType: AuthenticationType {
return options.authenticationType
}
public var accessibility: Accessibility {
return options.accessibility
}
@available(iOS 8.0, OSX 10.10, *)
@available(watchOS, unavailable)
public var authenticationPolicy: AuthenticationPolicy? {
return options.authenticationPolicy
}
public var synchronizable: Bool {
return options.synchronizable
}
public var label: String? {
return options.label
}
public var comment: String? {
return options.comment
}
@available(iOS 8.0, OSX 10.10, *)
@available(watchOS, unavailable)
public var authenticationPrompt: String? {
return options.authenticationPrompt
}
fileprivate let options: Options
// MARK:
public convenience init() {
var options = Options()
if let bundleIdentifier = Bundle.main.bundleIdentifier {
options.service = bundleIdentifier
}
self.init(options)
}
public convenience init(service: String) {
var options = Options()
options.service = service
self.init(options)
}
public convenience init(accessGroup: String) {
var options = Options()
if let bundleIdentifier = Bundle.main.bundleIdentifier {
options.service = bundleIdentifier
}
options.accessGroup = accessGroup
self.init(options)
}
public convenience init(service: String, accessGroup: String) {
var options = Options()
options.service = service
options.accessGroup = accessGroup
self.init(options)
}
public convenience init(server: String, protocolType: ProtocolType, authenticationType: AuthenticationType = .default) {
self.init(server: URL(string: server)!, protocolType: protocolType, authenticationType: authenticationType)
}
public convenience init(server: URL, protocolType: ProtocolType, authenticationType: AuthenticationType = .default) {
var options = Options()
options.itemClass = .internetPassword
options.server = server
options.protocolType = protocolType
options.authenticationType = authenticationType
self.init(options)
}
fileprivate init(_ opts: Options) {
options = opts
}
// MARK:
public func accessibility(_ accessibility: Accessibility) -> Keychain {
var options = self.options
options.accessibility = accessibility
return Keychain(options)
}
@available(iOS 8.0, OSX 10.10, *)
@available(watchOS, unavailable)
public func accessibility(_ accessibility: Accessibility, authenticationPolicy: AuthenticationPolicy) -> Keychain {
var options = self.options
options.accessibility = accessibility
options.authenticationPolicy = authenticationPolicy
return Keychain(options)
}
public func synchronizable(_ synchronizable: Bool) -> Keychain {
var options = self.options
options.synchronizable = synchronizable
return Keychain(options)
}
public func label(_ label: String) -> Keychain {
var options = self.options
options.label = label
return Keychain(options)
}
public func comment(_ comment: String) -> Keychain {
var options = self.options
options.comment = comment
return Keychain(options)
}
public func attributes(_ attributes: [String: Any]) -> Keychain {
var options = self.options
attributes.forEach { options.attributes.updateValue($1, forKey: $0) }
return Keychain(options)
}
@available(iOS 8.0, OSX 10.10, *)
@available(watchOS, unavailable)
public func authenticationPrompt(_ authenticationPrompt: String) -> Keychain {
var options = self.options
options.authenticationPrompt = authenticationPrompt
return Keychain(options)
}
// MARK:
public func get(_ key: String) throws -> String? {
return try getString(key)
}
public func getString(_ key: String) throws -> String? {
guard let data = try getData(key) else {
return nil
}
guard let string = String(data: data, encoding: .utf8) else {
print("failed to convert data to string")
throw Status.conversionError
}
return string
}
public func getData(_ key: String) throws -> Data? {
var query = options.query()
query[MatchLimit] = MatchLimitOne
query[ReturnData] = kCFBooleanTrue
query[AttributeAccount] = key
var result: AnyObject?
let status = SecItemCopyMatching(query as CFDictionary, &result)
switch status {
case errSecSuccess:
guard let data = result as? Data else {
throw Status.unexpectedError
}
return data
case errSecItemNotFound:
return nil
default:
throw securityError(status: status)
}
}
public func get<T>(_ key: String, handler: (Attributes?) -> T) throws -> T {
var query = options.query()
query[MatchLimit] = MatchLimitOne
query[ReturnData] = kCFBooleanTrue
query[ReturnAttributes] = kCFBooleanTrue
query[ReturnRef] = kCFBooleanTrue
query[ReturnPersistentRef] = kCFBooleanTrue
query[AttributeAccount] = key
var result: AnyObject?
let status = SecItemCopyMatching(query as CFDictionary, &result)
switch status {
case errSecSuccess:
guard let attributes = result as? [String: Any] else {
throw Status.unexpectedError
}
return handler(Attributes(attributes: attributes))
case errSecItemNotFound:
return handler(nil)
default:
throw securityError(status: status)
}
}
// MARK:
public func set(_ value: String, key: String) throws {
guard let data = value.data(using: .utf8, allowLossyConversion: false) else {
print("failed to convert string to data")
throw Status.conversionError
}
try set(data, key: key)
}
public func set(_ value: Data, key: String) throws {
var query = options.query()
query[AttributeAccount] = key
#if os(iOS)
if #available(iOS 9.0, *) {
query[UseAuthenticationUI] = UseAuthenticationUIFail
} else {
query[UseNoAuthenticationUI] = kCFBooleanTrue
}
#elseif os(OSX)
query[ReturnData] = kCFBooleanTrue
if #available(OSX 10.11, *) {
query[UseAuthenticationUI] = UseAuthenticationUIFail
}
#endif
var status = SecItemCopyMatching(query as CFDictionary, nil)
switch status {
case errSecSuccess, errSecInteractionNotAllowed:
var query = options.query()
query[AttributeAccount] = key
var (attributes, error) = options.attributes(key: nil, value: value)
if let error = error {
print(error.localizedDescription)
throw error
}
options.attributes.forEach { attributes.updateValue($1, forKey: $0) }
#if os(iOS)
if status == errSecInteractionNotAllowed && floor(NSFoundationVersionNumber) <= floor(NSFoundationVersionNumber_iOS_8_0) {
try remove(key)
try set(value, key: key)
} else {
status = SecItemUpdate(query as CFDictionary, attributes as CFDictionary)
if status != errSecSuccess {
throw securityError(status: status)
}
}
#else
status = SecItemUpdate(query as CFDictionary, attributes as CFDictionary)
if status != errSecSuccess {
throw securityError(status: status)
}
#endif
case errSecItemNotFound:
var (attributes, error) = options.attributes(key: key, value: value)
if let error = error {
print(error.localizedDescription)
throw error
}
options.attributes.forEach { attributes.updateValue($1, forKey: $0) }
status = SecItemAdd(attributes as CFDictionary, nil)
if status != errSecSuccess {
throw securityError(status: status)
}
default:
throw securityError(status: status)
}
}
public subscript(key: String) -> String? {
get {
return (try? get(key)).flatMap { $0 }
}
set {
if let value = newValue {
do {
try set(value, key: key)
} catch {}
} else {
do {
try remove(key)
} catch {}
}
}
}
public subscript(string key: String) -> String? {
get {
return self[key]
}
set {
self[key] = newValue
}
}
public subscript(data key: String) -> Data? {
get {
return (try? getData(key)).flatMap { $0 }
}
set {
if let value = newValue {
do {
try set(value, key: key)
} catch {}
} else {
do {
try remove(key)
} catch {}
}
}
}
public subscript(attributes key: String) -> Attributes? {
get {
return (try? get(key) { $0 }).flatMap { $0 }
}
}
// MARK:
public func remove(_ key: String) throws {
var query = options.query()
query[AttributeAccount] = key
let status = SecItemDelete(query as CFDictionary)
if status != errSecSuccess && status != errSecItemNotFound {
throw securityError(status: status)
}
}
public func removeAll() throws {
var query = options.query()
#if !os(iOS) && !os(watchOS) && !os(tvOS)
query[MatchLimit] = MatchLimitAll
#endif
let status = SecItemDelete(query as CFDictionary)
if status != errSecSuccess && status != errSecItemNotFound {
throw securityError(status: status)
}
}
// MARK:
public func contains(_ key: String) throws -> Bool {
var query = options.query()
query[AttributeAccount] = key
let status = SecItemCopyMatching(query as CFDictionary, nil)
switch status {
case errSecSuccess:
return true
case errSecItemNotFound:
return false
default:
throw securityError(status: status)
}
}
// MARK:
public class func allKeys(_ itemClass: ItemClass) -> [(String, String)] {
var query = [String: Any]()
query[Class] = itemClass.rawValue
query[AttributeSynchronizable] = SynchronizableAny
query[MatchLimit] = MatchLimitAll
query[ReturnAttributes] = kCFBooleanTrue
var result: AnyObject?
let status = SecItemCopyMatching(query as CFDictionary, &result)
switch status {
case errSecSuccess:
if let items = result as? [[String: Any]] {
return prettify(itemClass: itemClass, items: items).map {
switch itemClass {
case .genericPassword:
return (($0["service"] ?? "") as! String, ($0["key"] ?? "") as! String)
case .internetPassword:
return (($0["server"] ?? "") as! String, ($0["key"] ?? "") as! String)
}
}
}
case errSecItemNotFound:
return []
default: ()
}
securityError(status: status)
return []
}
public func allKeys() -> [String] {
return type(of: self).prettify(itemClass: itemClass, items: items()).map { $0["key"] as! String }
}
public class func allItems(_ itemClass: ItemClass) -> [[String: Any]] {
var query = [String: Any]()
query[Class] = itemClass.rawValue
query[MatchLimit] = MatchLimitAll
query[ReturnAttributes] = kCFBooleanTrue
#if os(iOS) || os(watchOS) || os(tvOS)
query[ReturnData] = kCFBooleanTrue
#endif
var result: AnyObject?
let status = SecItemCopyMatching(query as CFDictionary, &result)
switch status {
case errSecSuccess:
if let items = result as? [[String: Any]] {
return prettify(itemClass: itemClass, items: items)
}
case errSecItemNotFound:
return []
default: ()
}
securityError(status: status)
return []
}
public func allItems() -> [[String: Any]] {
return type(of: self).prettify(itemClass: itemClass, items: items())
}
#if os(iOS)
@available(iOS 8.0, *)
public func getSharedPassword(_ completion: @escaping (_ account: String?, _ password: String?, _ error: Error?) -> () = { account, password, error -> () in }) {
if let domain = server.host {
type(of: self).requestSharedWebCredential(domain: domain, account: nil) { (credentials, error) -> () in
if let credential = credentials.first {
let account = credential["account"]
let password = credential["password"]
completion(account, password, error)
} else {
completion(nil, nil, error)
}
}
} else {
let error = securityError(status: Status.param.rawValue)
completion(nil, nil, error)
}
}
#endif
#if os(iOS)
@available(iOS 8.0, *)
public func getSharedPassword(_ account: String, completion: @escaping (_ password: String?, _ error: Error?) -> () = { password, error -> () in }) {
if let domain = server.host {
type(of: self).requestSharedWebCredential(domain: domain, account: account) { (credentials, error) -> () in
if let credential = credentials.first {
if let password = credential["password"] {
completion(password, error)
} else {
completion(nil, error)
}
} else {
completion(nil, error)
}
}
} else {
let error = securityError(status: Status.param.rawValue)
completion(nil, error)
}
}
#endif
#if os(iOS)
@available(iOS 8.0, *)
public func setSharedPassword(_ password: String, account: String, completion: (_ error: Error?) -> () = { e -> () in }) {
setSharedPassword((password as String?)!, account: account, completion: completion)
}
#endif
#if os(iOS)
@available(iOS 8.0, *)
fileprivate func setSharedPassword(_ password: String?, account: String, completion: @escaping (_ error: Error?) -> () = { e -> () in }) {
if let domain = server.host {
SecAddSharedWebCredential(domain as CFString, account as CFString, password as CFString?) { error -> () in
if let error = error {
completion(error.error)
} else {
completion(nil)
}
}
} else {
let error = securityError(status: Status.param.rawValue)
completion(error)
}
}
#endif
#if os(iOS)
@available(iOS 8.0, *)
public func removeSharedPassword(_ account: String, completion: @escaping (_ error: Error?) -> () = { e -> () in }) {
setSharedPassword(nil, account: account, completion: completion)
}
#endif
#if os(iOS)
@available(iOS 8.0, *)
public class func requestSharedWebCredential(_ completion: @escaping (_ credentials: [[String: String]], _ error: Error?) -> () = { credentials, error -> () in }) {
requestSharedWebCredential(domain: nil, account: nil, completion: completion)
}
#endif
#if os(iOS)
@available(iOS 8.0, *)
public class func requestSharedWebCredential(domain: String, completion: @escaping (_ credentials: [[String: String]], _ error: Error?) -> () = { credentials, error -> () in }) {
requestSharedWebCredential(domain: domain, account: nil, completion: completion)
}
#endif
#if os(iOS)
@available(iOS 8.0, *)
public class func requestSharedWebCredential(domain: String, account: String, completion: @escaping (_ credentials: [[String: String]], _ error: Error?) -> () = { credentials, error -> () in }) {
requestSharedWebCredential(domain: Optional(domain), account: Optional(account)!, completion: completion)
}
#endif
#if os(iOS)
@available(iOS 8.0, *)
fileprivate class func requestSharedWebCredential(domain: String?, account: String?, completion: @escaping (_ credentials: [[String: String]], _ error: Error?) -> ()) {
SecRequestSharedWebCredential(domain as CFString?, account as CFString?) { (credentials, error) -> () in
var remoteError: NSError?
if let error = error {
remoteError = error.error
if remoteError?.code != Int(errSecItemNotFound) {
print("error:[\(remoteError!.code)] \(remoteError!.localizedDescription)")
}
}
if let credentials = credentials {
let credentials = (credentials as NSArray).map { credentials -> [String: String] in
var credential = [String: String]()
if let credentials = credentials as? [String: String] {
if let server = credentials[AttributeServer] {
credential["server"] = server
}
if let account = credentials[AttributeAccount] {
credential["account"] = account
}
if let password = credentials[SharedPassword] {
credential["password"] = password
}
}
return credential
}
completion(credentials, remoteError)
} else {
completion([], remoteError)
}
}
}
#endif
#if os(iOS)
/**
@abstract Returns a randomly generated password.
@return String password in the form xxx-xxx-xxx-xxx where x is taken from the sets "abcdefghkmnopqrstuvwxy", "ABCDEFGHJKLMNPQRSTUVWXYZ", "3456789" with at least one character from each set being present.
*/
@available(iOS 8.0, *)
public class func generatePassword() -> String {
return SecCreateSharedWebCredentialPassword()! as String
}
#endif
// MARK:
fileprivate func items() -> [[String: Any]] {
var query = options.query()
query[MatchLimit] = MatchLimitAll
query[ReturnAttributes] = kCFBooleanTrue
#if os(iOS) || os(watchOS) || os(tvOS)
query[ReturnData] = kCFBooleanTrue
#endif
var result: AnyObject?
let status = SecItemCopyMatching(query as CFDictionary, &result)
switch status {
case errSecSuccess:
if let items = result as? [[String: Any]] {
return items
}
case errSecItemNotFound:
return []
default: ()
}
securityError(status: status)
return []
}
fileprivate class func prettify(itemClass: ItemClass, items: [[String: Any]]) -> [[String: Any]] {
let items = items.map { attributes -> [String: Any] in
var item = [String: Any]()
item["class"] = itemClass.description
switch itemClass {
case .genericPassword:
if let service = attributes[AttributeService] as? String {
item["service"] = service
}
if let accessGroup = attributes[AttributeAccessGroup] as? String {
item["accessGroup"] = accessGroup
}
case .internetPassword:
if let server = attributes[AttributeServer] as? String {
item["server"] = server
}
if let proto = attributes[AttributeProtocol] as? String {
if let protocolType = ProtocolType(rawValue: proto) {
item["protocol"] = protocolType.description
}
}
if let auth = attributes[AttributeAuthenticationType] as? String {
if let authenticationType = AuthenticationType(rawValue: auth) {
item["authenticationType"] = authenticationType.description
}
}
}
if let key = attributes[AttributeAccount] as? String {
item["key"] = key
}
if let data = attributes[ValueData] as? Data {
if let text = String(data: data, encoding: .utf8) {
item["value"] = text
} else {
item["value"] = data
}
}
if let accessible = attributes[AttributeAccessible] as? String {
if let accessibility = Accessibility(rawValue: accessible) {
item["accessibility"] = accessibility.description
}
}
if let synchronizable = attributes[AttributeSynchronizable] as? Bool {
item["synchronizable"] = synchronizable ? "true" : "false"
}
return item
}
return items
}
// MARK:
@discardableResult
fileprivate class func securityError(status: OSStatus) -> Error {
let error = Status(status: status)
print("OSStatus error:[\(error.errorCode)] \(error.description)")
return error
}
@discardableResult
fileprivate func securityError(status: OSStatus) -> Error {
return type(of: self).securityError(status: status)
}
}
struct Options {
var itemClass: ItemClass = .genericPassword
var service: String = ""
var accessGroup: String? = nil
var server: URL!
var protocolType: ProtocolType!
var authenticationType: AuthenticationType = .default
var accessibility: Accessibility = .afterFirstUnlock
var authenticationPolicy: AuthenticationPolicy?
var synchronizable: Bool = false
var label: String?
var comment: String?
var authenticationPrompt: String?
var attributes = [String: Any]()
}
/** Class Key Constant */
private let Class = String(kSecClass)
/** Attribute Key Constants */
private let AttributeAccessible = String(kSecAttrAccessible)
@available(iOS 8.0, OSX 10.10, *)
private let AttributeAccessControl = String(kSecAttrAccessControl)
private let AttributeAccessGroup = String(kSecAttrAccessGroup)
private let AttributeSynchronizable = String(kSecAttrSynchronizable)
private let AttributeCreationDate = String(kSecAttrCreationDate)
private let AttributeModificationDate = String(kSecAttrModificationDate)
private let AttributeDescription = String(kSecAttrDescription)
private let AttributeComment = String(kSecAttrComment)
private let AttributeCreator = String(kSecAttrCreator)
private let AttributeType = String(kSecAttrType)
private let AttributeLabel = String(kSecAttrLabel)
private let AttributeIsInvisible = String(kSecAttrIsInvisible)
private let AttributeIsNegative = String(kSecAttrIsNegative)
private let AttributeAccount = String(kSecAttrAccount)
private let AttributeService = String(kSecAttrService)
private let AttributeGeneric = String(kSecAttrGeneric)
private let AttributeSecurityDomain = String(kSecAttrSecurityDomain)
private let AttributeServer = String(kSecAttrServer)
private let AttributeProtocol = String(kSecAttrProtocol)
private let AttributeAuthenticationType = String(kSecAttrAuthenticationType)
private let AttributePort = String(kSecAttrPort)
private let AttributePath = String(kSecAttrPath)
private let SynchronizableAny = kSecAttrSynchronizableAny
/** Search Constants */
private let MatchLimit = String(kSecMatchLimit)
private let MatchLimitOne = kSecMatchLimitOne
private let MatchLimitAll = kSecMatchLimitAll
/** Return Type Key Constants */
private let ReturnData = String(kSecReturnData)
private let ReturnAttributes = String(kSecReturnAttributes)
private let ReturnRef = String(kSecReturnRef)
private let ReturnPersistentRef = String(kSecReturnPersistentRef)
/** Value Type Key Constants */
private let ValueData = String(kSecValueData)
private let ValueRef = String(kSecValueRef)
private let ValuePersistentRef = String(kSecValuePersistentRef)
/** Other Constants */
@available(iOS 8.0, OSX 10.10, *)
private let UseOperationPrompt = String(kSecUseOperationPrompt)
#if os(iOS)
@available(iOS, introduced: 8.0, deprecated: 9.0, message: "Use a UseAuthenticationUI instead.")
private let UseNoAuthenticationUI = String(kSecUseNoAuthenticationUI)
#endif
@available(iOS 9.0, OSX 10.11, *)
@available(watchOS, unavailable)
private let UseAuthenticationUI = String(kSecUseAuthenticationUI)
@available(iOS 9.0, OSX 10.11, *)
@available(watchOS, unavailable)
private let UseAuthenticationContext = String(kSecUseAuthenticationContext)
@available(iOS 9.0, OSX 10.11, *)
@available(watchOS, unavailable)
private let UseAuthenticationUIAllow = String(kSecUseAuthenticationUIAllow)
@available(iOS 9.0, OSX 10.11, *)
@available(watchOS, unavailable)
private let UseAuthenticationUIFail = String(kSecUseAuthenticationUIFail)
@available(iOS 9.0, OSX 10.11, *)
@available(watchOS, unavailable)
private let UseAuthenticationUISkip = String(kSecUseAuthenticationUISkip)
#if os(iOS)
/** Credential Key Constants */
private let SharedPassword = String(kSecSharedPassword)
#endif
extension Keychain: CustomStringConvertible, CustomDebugStringConvertible {
public var description: String {
let items = allItems()
if items.isEmpty {
return "[]"
}
var description = "[\n"
for item in items {
description += " "
description += "\(item)\n"
}
description += "]"
return description
}
public var debugDescription: String {
return "\(items())"
}
}
extension Options {
func query() -> [String: Any] {
var query = [String: Any]()
query[Class] = itemClass.rawValue
query[AttributeSynchronizable] = SynchronizableAny
switch itemClass {
case .genericPassword:
query[AttributeService] = service
// 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[AttributeAccessGroup] = accessGroup
}
#endif
case .internetPassword:
query[AttributeServer] = server.host
query[AttributePort] = server.port
query[AttributeProtocol] = protocolType.rawValue
query[AttributeAuthenticationType] = authenticationType.rawValue
}
if #available(OSX 10.10, *) {
if authenticationPrompt != nil {
query[UseOperationPrompt] = authenticationPrompt
}
}
return query
}
func attributes(key: String?, value: Data) -> ([String: Any], Error?) {
var attributes: [String: Any]
if key != nil {
attributes = query()
attributes[AttributeAccount] = key
} else {
attributes = [String: Any]()
}
attributes[ValueData] = value
if label != nil {
attributes[AttributeLabel] = label
}
if comment != nil {
attributes[AttributeComment] = comment
}
if let policy = authenticationPolicy {
if #available(OSX 10.10, *) {
var error: Unmanaged<CFError>?
guard let accessControl = SecAccessControlCreateWithFlags(kCFAllocatorDefault, accessibility.rawValue as CFTypeRef, SecAccessControlCreateFlags(rawValue: CFOptionFlags(policy.rawValue)), &error) else {
if let error = error?.takeUnretainedValue() {
return (attributes, error.error)
}
return (attributes, Status.unexpectedError)
}
attributes[AttributeAccessControl] = accessControl
} else {
print("Unavailable 'Touch ID integration' on OS X versions prior to 10.10.")
}
} else {
attributes[AttributeAccessible] = accessibility.rawValue
}
attributes[AttributeSynchronizable] = synchronizable ? kCFBooleanTrue : kCFBooleanFalse
return (attributes, nil)
}
}
// MARK:
extension Attributes: CustomStringConvertible, CustomDebugStringConvertible {
public var description: String {
return "\(attributes)"
}
public var debugDescription: String {
return description
}
}
extension ItemClass: RawRepresentable, CustomStringConvertible {
public init?(rawValue: String) {
switch rawValue {
case String(kSecClassGenericPassword):
self = .genericPassword
case String(kSecClassInternetPassword):
self = .internetPassword
default:
return nil
}
}
public var rawValue: String {
switch self {
case .genericPassword:
return String(kSecClassGenericPassword)
case .internetPassword:
return String(kSecClassInternetPassword)
}
}
public var description: String {
switch self {
case .genericPassword:
return "GenericPassword"
case .internetPassword:
return "InternetPassword"
}
}
}
extension ProtocolType: RawRepresentable, CustomStringConvertible {
public init?(rawValue: String) {
switch rawValue {
case String(kSecAttrProtocolFTP):
self = .ftp
case String(kSecAttrProtocolFTPAccount):
self = .ftpAccount
case String(kSecAttrProtocolHTTP):
self = .http
case String(kSecAttrProtocolIRC):
self = .irc
case String(kSecAttrProtocolNNTP):
self = .nntp
case String(kSecAttrProtocolPOP3):
self = .pop3
case String(kSecAttrProtocolSMTP):
self = .smtp
case String(kSecAttrProtocolSOCKS):
self = .socks
case String(kSecAttrProtocolIMAP):
self = .imap
case String(kSecAttrProtocolLDAP):
self = .ldap
case String(kSecAttrProtocolAppleTalk):
self = .appleTalk
case String(kSecAttrProtocolAFP):
self = .afp
case String(kSecAttrProtocolTelnet):
self = .telnet
case String(kSecAttrProtocolSSH):
self = .ssh
case String(kSecAttrProtocolFTPS):
self = .ftps
case String(kSecAttrProtocolHTTPS):
self = .https
case String(kSecAttrProtocolHTTPProxy):
self = .httpProxy
case String(kSecAttrProtocolHTTPSProxy):
self = .httpsProxy
case String(kSecAttrProtocolFTPProxy):
self = .ftpProxy
case String(kSecAttrProtocolSMB):
self = .smb
case String(kSecAttrProtocolRTSP):
self = .rtsp
case String(kSecAttrProtocolRTSPProxy):
self = .rtspProxy
case String(kSecAttrProtocolDAAP):
self = .daap
case String(kSecAttrProtocolEPPC):
self = .eppc
case String(kSecAttrProtocolIPP):
self = .ipp
case String(kSecAttrProtocolNNTPS):
self = .nntps
case String(kSecAttrProtocolLDAPS):
self = .ldaps
case String(kSecAttrProtocolTelnetS):
self = .telnetS
case String(kSecAttrProtocolIMAPS):
self = .imaps
case String(kSecAttrProtocolIRCS):
self = .ircs
case String(kSecAttrProtocolPOP3S):
self = .pop3S
default:
return nil
}
}
public var rawValue: String {
switch self {
case .ftp:
return String(kSecAttrProtocolFTP)
case .ftpAccount:
return String(kSecAttrProtocolFTPAccount)
case .http:
return String(kSecAttrProtocolHTTP)
case .irc:
return String(kSecAttrProtocolIRC)
case .nntp:
return String(kSecAttrProtocolNNTP)
case .pop3:
return String(kSecAttrProtocolPOP3)
case .smtp:
return String(kSecAttrProtocolSMTP)
case .socks:
return String(kSecAttrProtocolSOCKS)
case .imap:
return String(kSecAttrProtocolIMAP)
case .ldap:
return String(kSecAttrProtocolLDAP)
case .appleTalk:
return String(kSecAttrProtocolAppleTalk)
case .afp:
return String(kSecAttrProtocolAFP)
case .telnet:
return String(kSecAttrProtocolTelnet)
case .ssh:
return String(kSecAttrProtocolSSH)
case .ftps:
return String(kSecAttrProtocolFTPS)
case .https:
return String(kSecAttrProtocolHTTPS)
case .httpProxy:
return String(kSecAttrProtocolHTTPProxy)
case .httpsProxy:
return String(kSecAttrProtocolHTTPSProxy)
case .ftpProxy:
return String(kSecAttrProtocolFTPProxy)
case .smb:
return String(kSecAttrProtocolSMB)
case .rtsp:
return String(kSecAttrProtocolRTSP)
case .rtspProxy:
return String(kSecAttrProtocolRTSPProxy)
case .daap:
return String(kSecAttrProtocolDAAP)
case .eppc:
return String(kSecAttrProtocolEPPC)
case .ipp:
return String(kSecAttrProtocolIPP)
case .nntps:
return String(kSecAttrProtocolNNTPS)
case .ldaps:
return String(kSecAttrProtocolLDAPS)
case .telnetS:
return String(kSecAttrProtocolTelnetS)
case .imaps:
return String(kSecAttrProtocolIMAPS)
case .ircs:
return String(kSecAttrProtocolIRCS)
case .pop3S:
return String(kSecAttrProtocolPOP3S)
}
}
public var description: String {
switch self {
case .ftp:
return "FTP"
case .ftpAccount:
return "FTPAccount"
case .http:
return "HTTP"
case .irc:
return "IRC"
case .nntp:
return "NNTP"
case .pop3:
return "POP3"
case .smtp:
return "SMTP"
case .socks:
return "SOCKS"
case .imap:
return "IMAP"
case .ldap:
return "LDAP"
case .appleTalk:
return "AppleTalk"
case .afp:
return "AFP"
case .telnet:
return "Telnet"
case .ssh:
return "SSH"
case .ftps:
return "FTPS"
case .https:
return "HTTPS"
case .httpProxy:
return "HTTPProxy"
case .httpsProxy:
return "HTTPSProxy"
case .ftpProxy:
return "FTPProxy"
case .smb:
return "SMB"
case .rtsp:
return "RTSP"
case .rtspProxy:
return "RTSPProxy"
case .daap:
return "DAAP"
case .eppc:
return "EPPC"
case .ipp:
return "IPP"
case .nntps:
return "NNTPS"
case .ldaps:
return "LDAPS"
case .telnetS:
return "TelnetS"
case .imaps:
return "IMAPS"
case .ircs:
return "IRCS"
case .pop3S:
return "POP3S"
}
}
}
extension AuthenticationType: RawRepresentable, CustomStringConvertible {
public init?(rawValue: String) {
switch rawValue {
case String(kSecAttrAuthenticationTypeNTLM):
self = .ntlm
case String(kSecAttrAuthenticationTypeMSN):
self = .msn
case String(kSecAttrAuthenticationTypeDPA):
self = .dpa
case String(kSecAttrAuthenticationTypeRPA):
self = .rpa
case String(kSecAttrAuthenticationTypeHTTPBasic):
self = .httpBasic
case String(kSecAttrAuthenticationTypeHTTPDigest):
self = .httpDigest
case String(kSecAttrAuthenticationTypeHTMLForm):
self = .htmlForm
case String(kSecAttrAuthenticationTypeDefault):
self = .`default`
default:
return nil
}
}
public var rawValue: String {
switch self {
case .ntlm:
return String(kSecAttrAuthenticationTypeNTLM)
case .msn:
return String(kSecAttrAuthenticationTypeMSN)
case .dpa:
return String(kSecAttrAuthenticationTypeDPA)
case .rpa:
return String(kSecAttrAuthenticationTypeRPA)
case .httpBasic:
return String(kSecAttrAuthenticationTypeHTTPBasic)
case .httpDigest:
return String(kSecAttrAuthenticationTypeHTTPDigest)
case .htmlForm:
return String(kSecAttrAuthenticationTypeHTMLForm)
case .`default`:
return String(kSecAttrAuthenticationTypeDefault)
}
}
public var description: String {
switch self {
case .ntlm:
return "NTLM"
case .msn:
return "MSN"
case .dpa:
return "DPA"
case .rpa:
return "RPA"
case .httpBasic:
return "HTTPBasic"
case .httpDigest:
return "HTTPDigest"
case .htmlForm:
return "HTMLForm"
case .`default`:
return "Default"
}
}
}
extension Accessibility: RawRepresentable, CustomStringConvertible {
public init?(rawValue: String) {
if #available(OSX 10.10, *) {
switch rawValue {
case String(kSecAttrAccessibleWhenUnlocked):
self = .whenUnlocked
case String(kSecAttrAccessibleAfterFirstUnlock):
self = .afterFirstUnlock
case String(kSecAttrAccessibleAlways):
self = .always
case String(kSecAttrAccessibleWhenPasscodeSetThisDeviceOnly):
self = .whenPasscodeSetThisDeviceOnly
case String(kSecAttrAccessibleWhenUnlockedThisDeviceOnly):
self = .whenUnlockedThisDeviceOnly
case String(kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly):
self = .afterFirstUnlockThisDeviceOnly
case String(kSecAttrAccessibleAlwaysThisDeviceOnly):
self = .alwaysThisDeviceOnly
default:
return nil
}
} else {
switch rawValue {
case String(kSecAttrAccessibleWhenUnlocked):
self = .whenUnlocked
case String(kSecAttrAccessibleAfterFirstUnlock):
self = .afterFirstUnlock
case String(kSecAttrAccessibleAlways):
self = .always
case String(kSecAttrAccessibleWhenUnlockedThisDeviceOnly):
self = .whenUnlockedThisDeviceOnly
case String(kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly):
self = .afterFirstUnlockThisDeviceOnly
case String(kSecAttrAccessibleAlwaysThisDeviceOnly):
self = .alwaysThisDeviceOnly
default:
return nil
}
}
}
public var rawValue: String {
switch self {
case .whenUnlocked:
return String(kSecAttrAccessibleWhenUnlocked)
case .afterFirstUnlock:
return String(kSecAttrAccessibleAfterFirstUnlock)
case .always:
return String(kSecAttrAccessibleAlways)
case .whenPasscodeSetThisDeviceOnly:
if #available(OSX 10.10, *) {
return String(kSecAttrAccessibleWhenPasscodeSetThisDeviceOnly)
} else {
fatalError("'Accessibility.WhenPasscodeSetThisDeviceOnly' is not available on this version of OS.")
}
case .whenUnlockedThisDeviceOnly:
return String(kSecAttrAccessibleWhenUnlockedThisDeviceOnly)
case .afterFirstUnlockThisDeviceOnly:
return String(kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly)
case .alwaysThisDeviceOnly:
return String(kSecAttrAccessibleAlwaysThisDeviceOnly)
}
}
public var description: String {
switch self {
case .whenUnlocked:
return "WhenUnlocked"
case .afterFirstUnlock:
return "AfterFirstUnlock"
case .always:
return "Always"
case .whenPasscodeSetThisDeviceOnly:
return "WhenPasscodeSetThisDeviceOnly"
case .whenUnlockedThisDeviceOnly:
return "WhenUnlockedThisDeviceOnly"
case .afterFirstUnlockThisDeviceOnly:
return "AfterFirstUnlockThisDeviceOnly"
case .alwaysThisDeviceOnly:
return "AlwaysThisDeviceOnly"
}
}
}
extension CFError {
var error: NSError {
let domain = CFErrorGetDomain(self) as String
let code = CFErrorGetCode(self)
let userInfo = CFErrorCopyUserInfo(self) as! [NSObject: Any]
return NSError(domain: domain, code: code, userInfo: userInfo)
}
}
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."
}
}
}
extension Status: CustomNSError {
public static var errorDomain: String {
return KeychainAccessErrorDomain
}
public var errorCode: Int {
return Int(rawValue)
}
public var errorUserInfo: [String : Any] {
return [NSLocalizedDescriptionKey: description]
}
}
| lgpl-2.1 | 10b84b6ba21500bfe3f1d6e908ac2196 | 38.803738 | 217 | 0.604211 | 5.537028 | false | false | false | false |
clappr/clappr-ios | Sources/Clappr_iOS/Classes/Animation/SeekBubble/SeekBubble.swift | 1 | 10172 | class SeekBubble: UIView {
private var label = UILabel()
private var images: [UIImageView] = []
private var text: String!
private weak var parentView: UIView?
var bubbleHeight = NSLayoutConstraint()
var bubbleWidth = NSLayoutConstraint()
var bubbleSide: SeekBubbleSide!
func setup(within parentView: UIView, bubbleSide: SeekBubbleSide, text: String = "10 segundos", numberOfIndicators: Int = 3) {
self.parentView = parentView
self.bubbleSide = bubbleSide
self.text = text
parentView.clipsToBounds = true
setupBubble(within: parentView, position: bubbleSide.position())
setupLabel(parentView, position: bubbleSide.positionConstant())
setupImages(numberOfIndicators)
}
func animate() {
animateBubble()
animateLabel()
animateImages()
}
private func animateBubble() {
guard let parentView = parentView else { return }
parentView.bringSubviewToFront(self)
bubbleWidth.constant = parentView.frame.width
bubbleHeight.constant = parentView.frame.height * 1.8
UIView.animate(withDuration: ClapprAnimationDuration.seekBubbleShow, animations: {
self.alpha = 1.0
self.addRoundedBorder(with: self.bubbleHeight.constant / 2)
parentView.layoutSubviews()
}, completion: { _ in
UIView.animate(withDuration: ClapprAnimationDuration.seekBubbleHide, delay: ClapprAnimationDuration.seekBubbleVisibility, animations: {
self.alpha = 0.0
parentView.layoutSubviews()
}, completion: { _ in
self.bubbleHeight.constant = 0
self.bubbleWidth.constant = 0
parentView.layoutSubviews()
})
})
}
private func animateLabel() {
parentView?.bringSubviewToFront(label)
UIView.animate(withDuration: ClapprAnimationDuration.seekLabelShow, animations: {
self.label.alpha = 1.0
self.parentView?.layoutSubviews()
}, completion: { _ in
UIView.animate(withDuration: ClapprAnimationDuration.seekLabelHide, delay: ClapprAnimationDuration.seekLabelVisibility, animations: {
self.label.alpha = 0.0
self.parentView?.layoutSubviews()
})
})
}
private func animateImages() {
var delay: TimeInterval = 0
let orderedImages = bubbleSide == .left ? images.reversed() : images
for index in 0..<orderedImages.count {
let image = orderedImages[index]
animate(image, delay: delay)
delay += 0.2
}
}
private func animate(_ image: UIImageView, delay: TimeInterval) {
parentView?.bringSubviewToFront(image)
UIView.animate(withDuration: ClapprAnimationDuration.seekImageShow, delay: delay, animations: {
image.alpha = 1.0
self.parentView?.layoutSubviews()
}, completion: { _ in
UIView.animate(withDuration: ClapprAnimationDuration.seekImageHide, delay: ClapprAnimationDuration.seekImageVisibility, animations: {
image.alpha = 0.0
self.parentView?.layoutSubviews()
})
})
}
private func setupImages(_ numberOfIndicators: Int) {
guard let parentView = parentView else { return }
let positionModifier: CGFloat = -14.0
var currentPosition = positionModifier
for _ in 0..<numberOfIndicators {
let image = bubbleSide.image()
setupImage(parentView, image: image, constX: currentPosition)
currentPosition -= positionModifier
images.append(image)
}
}
private func setupBubble(within view: UIView, position: NSLayoutConstraint.Attribute) {
backgroundColor = UIColor(white: 0, alpha: 0.2)
view.addSubview(self)
translatesAutoresizingMaskIntoConstraints = false
view.addConstraint(NSLayoutConstraint(item: self,
attribute: .centerY,
relatedBy: .equal,
toItem: view,
attribute: .centerY,
multiplier: 1,
constant: 0))
view.addConstraint(NSLayoutConstraint(item: self,
attribute: .centerX,
relatedBy: .equal,
toItem: view,
attribute: position,
multiplier: 1,
constant: 0))
bubbleWidth = NSLayoutConstraint(item: self,
attribute: .width,
relatedBy: .equal,
toItem: nil,
attribute: .width,
multiplier: 1,
constant: 0)
bubbleHeight = NSLayoutConstraint(item: self,
attribute: .height,
relatedBy: .equal,
toItem: nil,
attribute: .height,
multiplier: 1,
constant: 0)
let constraints = [bubbleWidth, bubbleHeight]
constraints.forEach { $0.isActive = true }
self.addConstraints(constraints)
}
private func setupLabel(_ view: UIView, position: CGFloat) {
label.text = text
label.textColor = .white
label.textAlignment = .center
label.font = UIFont.boldSystemFont(ofSize: 13)
label.alpha = 0.0
view.addSubview(label)
label.translatesAutoresizingMaskIntoConstraints = false
view.addConstraint(NSLayoutConstraint(item: label,
attribute: .width,
relatedBy: .equal,
toItem: nil,
attribute: .width,
multiplier: 1,
constant: 128))
view.addConstraint(NSLayoutConstraint(item: label,
attribute: .height,
relatedBy: .equal,
toItem: nil,
attribute: .height,
multiplier: 1,
constant: 32))
view.addConstraint(NSLayoutConstraint(item: label,
attribute: .centerX,
relatedBy: .equal,
toItem: view,
attribute: .centerX,
multiplier: position,
constant: 0))
view.addConstraint(NSLayoutConstraint(item: label,
attribute: .centerY,
relatedBy: .equal,
toItem: view,
attribute: .centerY,
multiplier: 1,
constant: 0))
}
private func setupImage(_ view: UIView, image: UIImageView, constX: CGFloat) {
image.alpha = 0.0
view.addSubview(image)
image.translatesAutoresizingMaskIntoConstraints = false
view.addConstraint(NSLayoutConstraint(item: image,
attribute: .width,
relatedBy: .equal,
toItem: nil,
attribute: .width,
multiplier: 1,
constant: 14))
view.addConstraint(NSLayoutConstraint(item: image,
attribute: .height,
relatedBy: .equal,
toItem: nil,
attribute: .height,
multiplier: 1,
constant: 14))
view.addConstraint(NSLayoutConstraint(item: image,
attribute: .centerX,
relatedBy: .equal,
toItem: label,
attribute: .centerX,
multiplier: 1,
constant: constX))
view.addConstraint(NSLayoutConstraint(item: image,
attribute: .top,
relatedBy: .equal,
toItem: label,
attribute: .top,
multiplier: 1,
constant: 36))
}
}
| bsd-3-clause | ca567bea204ca549d1975199dbbf8ae6 | 43.614035 | 147 | 0.432855 | 7.015172 | false | false | false | false |
maximedegreve/TinyFaces | Sources/App/Migrations/CreateFirstName.swift | 1 | 2251 | import Fluent
import Vapor
struct CreateFirstName: Migration {
var app: Application
init(app: Application) {
self.app = app
}
func prepare(on database: Database) -> EventLoopFuture<Void> {
database.enum("genders").read().flatMap { genderType in
return database.schema("first_names")
.field(.id, .int, .identifier(auto: true), .required)
.field("name", .string, .required)
.field("gender", genderType, .required)
.field("created_at", .datetime)
.field("updated_at", .datetime)
.field("deleted_at", .datetime)
.create().flatMap { () in
return seed(on: database, gender: .Female, filePath: "/Resources/Data/FirstNamesFemale.txt").flatMap { () in
return seed(on: database, gender: .Male, filePath: "/Resources//Data/FirstNamesMale.txt").flatMap { () in
return seed(on: database, gender: .NonBinary, filePath: "/Resources/Data/FirstNamesOther.txt")
}
}
}
}
}
func seed(on database: Database, gender: Gender, filePath: String) -> EventLoopFuture<Void> {
guard let txtFileContents = try? String(contentsOfFile: app.directory.workingDirectory + filePath, encoding: .utf8) else {
return database.eventLoop.makeFailedFuture(Abort(.badRequest, reason: "File not found for seeding."))
}
let txtLines = txtFileContents.components(separatedBy: "\n").filter {!$0.isEmpty}
return save(names: txtLines, index: 0, gender: gender, on: database)
}
func save(names: [String], index: Int, gender: Gender, on database: Database) -> EventLoopFuture<Void> {
guard let name = names[safe: index] else {
return database.eventLoop.future()
}
let newName = FirstName(name: name, gender: gender)
return newName.save(on: database).flatMap { () in
return save(names: names, index: index + 1, gender: gender, on: database)
}
}
func revert(on database: Database) -> EventLoopFuture<Void> {
return database.schema("last_names").delete()
}
}
| mit | 3d0bc130d107dbf3c113f4527b313ffb | 38.491228 | 130 | 0.58996 | 4.387914 | false | false | false | false |
Jauzee/showroom | Showroom/ViewControllers/SearchViewController/SearchViewController.swift | 1 | 2740 | import UIKit
import RAMReel
import RxSwift
import RxCocoa
class SearchViewController: UIViewController {
let viewModel: ReelSearchViewModel
var bag = DisposeBag()
private var ramReel: RAMReel<RAMCell, RAMTextField, SimplePrefixQueryDataSource>!
private let loadingOverlay = UIView()
private let loadingIndicator = UIActivityIndicatorView(activityIndicatorStyle: .whiteLarge)
init(viewModel: ReelSearchViewModel) {
self.viewModel = viewModel
super.init(nibName: nil, bundle: nil)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .white
setupReelSearch()
setupLoadingIndicator()
MenuPopUpViewController.showPopup(on: self, url: Showroom.Control.reelSearch.sharedURL) { [weak self] in
self?.dismiss(animated: true, completion: nil)
self?.dismiss(animated: true, completion: nil)
}
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
ThingersTapViewController.showPopup(on: self)
}
override func viewWillLayoutSubviews() {
super.viewWillLayoutSubviews()
loadingIndicator.center = loadingOverlay.center
}
private func setupReelSearch() {
viewModel.dataSource.asObservable()
.skip(1) // skip initial empty value
.observeOn(MainScheduler.instance)
.subscribe(onNext: { dataSource in
self.ramReel = RAMReel(frame: self.view.bounds, dataSource: dataSource, placeholder: "Start by typing…") {
print("Plain:", $0)
}
self.ramReel.hooks.append {
let r = Array($0.characters.reversed())
let j = String(r)
print("Reversed:", j)
}
self.view.addSubview(self.ramReel.view)
self.ramReel.view.autoresizingMask = [.flexibleWidth, .flexibleHeight]
self.hideOverlay(true)
})
.addDisposableTo(bag)
}
private func setupLoadingIndicator() {
loadingOverlay.backgroundColor = UIColor.black.withAlphaComponent(0.6)
loadingOverlay.autoresizingMask = [.flexibleWidth, .flexibleHeight]
loadingOverlay.frame = view.bounds
view.addSubview(loadingOverlay)
loadingIndicator.color = .white
loadingIndicator.startAnimating()
loadingIndicator.frame = loadingOverlay.bounds
loadingOverlay.addSubview(loadingIndicator)
loadingIndicator.center = loadingOverlay.center
}
private func hideOverlay(_ value: Bool = true) {
UIView.animate(withDuration: 0.3) {
self.loadingOverlay.alpha = value ? 0 : 1
}
}
override open var shouldAutorotate: Bool {
return false
}
}
| gpl-3.0 | 568459f04f4868e5c199123f0ad97289 | 28.76087 | 114 | 0.691746 | 4.664395 | false | false | false | false |
wftllc/hahastream | Haha Stream/Features/Content List/ContentListInlineVideoInteractor.swift | 1 | 1881 | import Foundation
protocol ContentListInlineVideoInteractor: ContentListInteractor {
weak var inlineView: ContentListInlineVideoView? { get }
func viewDidHighlight(item: ContentItem)
func viewDidUnhighlight(item: ContentItem)
func viewDidTapInlinePreview()
}
class ContentListInlineVideoInteractorImpl: ContentListInteractorImpl, ContentListInlineVideoInteractor {
var inlineView: ContentListInlineVideoView? { get {
return self.viewStorage as? ContentListInlineVideoView
}
}
var videoPlayer: InlineVideoPlayer?
var highlightedGame: Game?
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
self.stopVideo()
}
func viewDidHighlight(item: ContentItem) {
guard let game = item.game else {
return
}
highlightedGame = game
provider.getStreams(game: game, success: { [weak self] (streams) in
self?.provider.getStreamURL(forStream: streams[0], inGame: game, success: { (streamURL) in
if self?.highlightedGame == game {
self?.previewVideo(url: streamURL.url)
}
}, apiError: { _ in },
networkFailure: { _ in }
)
}, apiError: { _ in },
networkFailure: { _ in }
)
}
func viewDidUnhighlight(item: ContentItem) {
stopVideo()
}
func viewDidTapInlinePreview() {
}
private func previewVideo(url: URL) {
print("\(#function) \(url.absoluteString))")
self.videoPlayer = InlineVideoPlayer(url: url)
videoPlayer?.load( ready: { [unowned self] in
self.videoPlayer?.play()
self.inlineView?.showVideo(player: self.videoPlayer!.player!)
}, failure: { [unowned self] error in
print("video load failure: \(error)")
self.stopVideo()
}, progress: nil,
completion: { [unowned self] in
self.stopVideo()
})
}
private func stopVideo() {
print("\(#function)")
self.videoPlayer?.stop()
self.videoPlayer = nil
self.inlineView?.hideVideo()
}
}
| mit | 292efdda46e0af8b9330d2a306025dd9 | 25.492958 | 106 | 0.709729 | 3.576046 | false | false | false | false |
daniel-barros/TV-Calendar | TV Calendar/MainViewController.swift | 1 | 24840 | //
// MainViewController.swift
// TV Calendar
//
// Created by Daniel Barros López on 10/8/16.
// Copyright © 2016 Daniel Barros. All rights reserved.
//
import ExtendedUIKit
// TODO: Use content view with different view controllers for .tracking, .searching and .trending.
/// 3 states: .tracking, where the user sees his tracked shows, .searching, where the user can search and add a show to his tracked shows list, .trending, where the user sees the trending shows.
class MainViewController: PaginatedTableViewController {
fileprivate enum Constants {
static let rowAnimationsDuration = 0.6
static let searchBarBeginEditingAnimationDuration = 0.5
static let showCellHeight: CGFloat = 116
static let loadingCellHeight: CGFloat = 46
}
@IBOutlet weak var searchBar: UISearchBar!
@IBOutlet var noContentLabels: [UILabel]!
@IBOutlet weak var noResultsLabel: UILabel!
@IBOutlet weak var doneButton: UIButton!
@IBOutlet weak var searchBarTrailingConstraint: NSLayoutConstraint!
@IBOutlet weak var searchBarToDoneButtonHorizontalConstraint: NSLayoutConstraint!
enum State {
case searching, tracking, trending
}
var state = State.tracking {
didSet {
switch state {
case .tracking:
dataSource = persistentDataSource
paginates = true
case .searching, .trending:
dataSource = temporaryDataSource
paginates = false
}
}
}
fileprivate var persistentDataSource = TrackedShowsTableViewDataSource.default // (mock init)
fileprivate var temporaryDataSource = TemporaryShowsTableViewDataSource.default // (mock init)
fileprivate var _showUpdater = ShowUpdater() // (mock init)
var showUpdater: ShowUpdater {
get { assert(_showUpdater.delegate != nil, "Set proper ShowUpdater calling configure()");
return _showUpdater }
set { _showUpdater = newValue }
}
fileprivate var _showTracker = ShowTracker.default // (mock init)
var showTracker: ShowTracker {
get { assert(_showTracker.delegate != nil, "Set proper ShowTracker calling configure()");
return _showTracker }
set { _showTracker = newValue }
}
fileprivate var _calendarSettingsManager = CalendarSettingsManager.default // (mock init)
var calendarSettingsManager: CalendarSettingsManager {
get { assert(_calendarSettingsManager.delegate != nil, "Set proper CalendarSettingsManager calling configure()");
return _calendarSettingsManager }
set { _calendarSettingsManager = newValue }
}
var calendarEventsManager = CalendarEventsManager.default // (mock init)
fileprivate let searchController = ShowSearchController()
fileprivate let trendingShowsController = TrendingShowsController()
fileprivate weak var presentedShowDetailViewController: ShowDetailViewController?
override func viewDidLoad() {
super.viewDidLoad()
paginationDelegate = self
searchController.delegate = self
trendingShowsController.delegate = self
updateNoContentLabels()
}
override func viewDidAppear(_ animated: Bool) {
let row = selectedRow
super.viewDidAppear(animated)
// Removes tracked show cell for show that was just untracked by the detail vc, right after it is popped from nav controller
if let detailVCShow = presentedShowDetailViewController?.show {
switch state {
case .tracking:
guard let indexPath = row else {
assertionFailure(); return
}
if detailVCShow.isInvalidated || !showTracker.isTracking(detailVCShow) {
deleteRow(at: indexPath) // Show was untracked
} else {
updateTable() // Show might have changed (deleted and then added again in detailVC) (currently no longer possible, since vc is popped right after untracking show)
}
case .searching, .trending: break
}
}
}
func configure(showUpdater: ShowUpdater, showTracker: ShowTracker, calendarSettingsManager: CalendarSettingsManager, calendarEventsManager: CalendarEventsManager) {
self.persistentDataSource = TrackedShowsTableViewDataSource(persistentShows: showTracker.trackedShows)
self.temporaryDataSource = TemporaryShowsTableViewDataSource(persistentShows: showTracker.trackedShows)
self.showUpdater = showUpdater
self.showTracker = showTracker
self.calendarSettingsManager = calendarSettingsManager
self.calendarEventsManager = calendarEventsManager
(self.state = self.state) // (forcing dataSource to update)
}
/// Stops the search and displays the tracked shows again.
@IBAction func cancelSearch(_ sender: Any) {
UIApplication.shared.isNetworkActivityIndicatorVisible = false
state = .tracking
temporaryDataSource.clearTemporaryShows()
trendingShowsController.cancelFetchOperations()
updateTable()
updateSearchUI()
updateSearchErrorLabel()
if tableView.numberOfSections > 0 && tableView.numberOfRows(inSection: 0) > 0 {
tableView.scrollToRow(at: IndexPath(row: 0, section: 0), at: .top, animated: false)
}
searchBar.resignFirstResponder()
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if let vc = segue.destination as? ShowDetailViewController,
let cell = sender as? ShowTableViewCell,
let show = cell.show {
// Hide keyboard if searching
if searchBar.isFirstResponder {
searchBar.resignFirstResponder()
}
// Start fetching episodes so info is ready if user tries to track the show
if !show.hasEpisodesInfo {
showUpdater.update(.episodes, for: show)
}
// Get poster if missing
if show.poster == nil {
showUpdater.update(.poster(replaceExisting: false), for: show)
}
// Configure show detail vc
vc.configure(with: show, calendarSettingsManager: calendarSettingsManager, calendarEventsManager: calendarEventsManager)
vc.delegate = self
presentedShowDetailViewController = vc
if state == .tracking && selectedRow == nil { // happens when coming from peek & pop
selectedRow = persistentDataSource.indexPath(for: show)
}
} else {
assertionFailure("Unknown segue destination")
}
}
override func updateTable() {
super.updateTable()
updateNoContentLabels()
}
override func headerName(forSection section: Int) -> String? {
switch state {
case .trending: return temporaryDataSource.temporaryShows.isEmpty ? nil : "Trending"
case .searching: return temporaryDataSource.temporaryShows.isEmpty ? nil : "Search Results"
case .tracking: return persistentDataSource.name(forSection: section)
}
}
}
// MARK: - PaginatedShowTableViewControllerDelegate
extension MainViewController: PaginatedTableViewControllerDelegate {
/// The position where the "waiting for new season" or "ended" sections begin.
func yPositionOfSecondPage(in tableView: UITableView, viewController: PaginatedTableViewController) -> CGFloat? {
guard state == .tracking else { return nil }
let lastSection = tableView.numberOfSections - 1
if lastSection < 1 {
return nil
}
if !persistentDataSource.endedGroupCorresponds(to: lastSection)
&& !persistentDataSource.waitingForNewSeasonGroupCorresponds(to: lastSection) {
return nil
}
var pageRect = tableView.rect(forSection: lastSection)
if persistentDataSource.waitingForNewSeasonGroupCorresponds(to: lastSection - 1) {
pageRect = pageRect.union(tableView.rect(forSection: lastSection - 1))
}
return pageRect.origin.y
}
/// The height needed for the next section's header to show, indicating there's a second page below.
func heightOfSecondPagePeekArea(in tableView: UITableView, viewController: PaginatedTableViewController) -> CGFloat {
return ShowGroupHeaderView.Constants.preferredHeight
}
}
// MARK: - ShowSearchControllerDelegate
extension MainViewController: ShowSearchControllerDelegate {
func obtainedSearchResults(_ result: Result<[Show]>, page: Int, limit: Int, from searchController: ShowSearchController) {
guard state == .searching else { return }
if page == 0 {
showUpdater.cancelOngoingPosterUpdates()
temporaryDataSource.populateTemporaryShows(with: result.value ?? [])
} else {
temporaryDataSource.extendTemporaryShows(with: result.value ?? [])
}
temporaryDataSource.isLoadingCellVisible = result.value?.count == limit
updateSearchErrorLabel(with: result.error as? Show.FetchError)
updateTable()
if page == 0 && tableView.numberOfRows(inSection: 0) > 0 {
tableView.scrollToRow(at: IndexPath(row: 0, section: 0), at: .top, animated: true)
}
if let shows = result.value {
showUpdater.update(.poster(replaceExisting: false), for: temporaryDataSource.temporaryShows[page*limit..<page*limit+shows.count])
}
}
}
// MARK; - TrendingShowsControllerDelegate
extension MainViewController: TrendingShowsControllerDelegate {
func obtainedTrendingShows(_ result: Result<[Show]>, page: Int, limit: Int, from controller: TrendingShowsController) {
guard state == .trending else { return }
UIApplication.shared.isNetworkActivityIndicatorVisible = false
if let shows = result.value {
if page == 0 {
temporaryDataSource.populateTemporaryShows(with: shows)
} else {
temporaryDataSource.extendTemporaryShows(with: shows)
}
temporaryDataSource.isLoadingCellVisible = shows.count == limit
showUpdater.update(.poster(replaceExisting: false),
for: temporaryDataSource.temporaryShows[page*limit..<page*limit+shows.count])
} else {
// No error messages (this was not directly requested by the user)
temporaryDataSource.isLoadingCellVisible = false
}
updateTable()
}
}
// MARK: - ShowUpdaterDelegate
extension MainViewController: ShowUpdaterDelegate {
// (Call forwarded from AppDelegate)
func didUpdate(_ updateType: ShowUpdater.UpdateType, for show: Show, withSuccess success: Bool, error: Show.FetchError?, info: [String: Any]?, updater: ShowUpdater) {
guard isViewLoaded else { return }
// Make UI updates when a show is updated
switch updateType {
case .airedEpisodes, .timeZone:
switch state {
case .tracking: updateTable()
case .searching, .trending: break
}
case .poster, .outdatedInfo, .episodes:
if success {
updateCellAndDetailVC(for: show)
}
// Update posters in trending shows cache too
if case .poster = updateType, state == .trending {
trendingShowsController.updateCachedShowsInfo(with: [show])
}
}
}
func didEndAllUpdates(updater: ShowUpdater) { }
}
// MARK: - UISearchBarDelegate
extension MainViewController: UISearchBarDelegate {
func searchBarShouldBeginEditing(_ searchBar: UISearchBar) -> Bool {
switch state {
case .tracking:
// Transition to trending shows
updateSearchUI(forNewState: .trending)
// without fade animation (content already available)
if trendingShowsController.hasCache {
state = .trending
updateTablePages()
updateNoContentLabels()
if tableView.numberOfSections > 0 && tableView.numberOfRows(inSection: 0) > 0 {
tableView.scrollToRow(at: IndexPath(row: 0, section: 0), at: .top, animated: false)
}
trendingShowsController.fetchTrendingShows(nextPosition: 0)
}
// with fade animation (content will be fetched)
else {
fadeTableToWhite(completion: {
self.state = .trending
self.updateTablePages()
self.updateNoContentLabels()
UIApplication.shared.isNetworkActivityIndicatorVisible = true
self.trendingShowsController.fetchTrendingShows(nextPosition: 0)
})
}
case .searching, .trending:
break
}
return true
}
func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
switch state {
case .searching:
// Back to trending
if searchText == "" {
state = .trending
temporaryDataSource.clearTemporaryShows()
updateTable()
updateSearchErrorLabel()
trendingShowsController.fetchTrendingShows(nextPosition: 0)
}
// Update search
else {
searchController.search(searchText)
updateSearchErrorLabel()
}
case .trending:
// Start searching
if searchText != "" {
trendingShowsController.cancelFetchOperations()
state = .searching
// TODO: Fade to white
temporaryDataSource.clearTemporaryShows()
temporaryDataSource.isLoadingCellVisible = false
updateTable()
searchController.search(searchText)
} else {
assertionFailure()
}
case .tracking:
assertionFailure()
}
}
}
// MARK: - UIScrollViewDelegate
extension MainViewController {
func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
// Hide keyboard if scrolling in search mode and there's some content
switch state {
case .searching, .trending:
if searchBar.isFirstResponder && !temporaryDataSource.temporaryShows.isEmpty {
searchBar.resignFirstResponder()
}
case .tracking:
break
}
}
}
// MARK: - UITableViewDelegate
extension MainViewController {
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if state == .tracking {
// let show = persistentDataSource.persistentShow(at: indexPath)
}
}
func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? {
switch state {
case .tracking:
return [
UITableViewRowAction(style: .destructive, title: "Stop Tracking")
{ [weak self] action, indexPath in
guard let `self` = self else { return }
let show = self.persistentDataSource.persistentShow(at: indexPath)
self.initiateStopTracking(of: show, sender: indexPath)
}
]
case .searching, .trending:
return nil
}
}
func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
(cell as? SearchShowTableViewCell)?.delegate = self
// Displaying loading cell triggers fetch of more results
if cell.reuseIdentifier == UITableViewCell.loadingCellReuseIdentifier {
assert(cell.contentView.subviews.first is UIActivityIndicatorView)
(cell.contentView.subviews.first as? UIActivityIndicatorView)?.startAnimating()
switch state {
case .trending:
if !trendingShowsController.isFetching {
trendingShowsController.fetchTrendingShows(nextPosition: temporaryDataSource.temporaryShows.count)
}
case .searching:
if !searchController.isSearching {
searchController.fetchMoreResults(nextPosition: temporaryDataSource.temporaryShows.count)
}
case .tracking:
assertionFailure()
}
}
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
switch state {
case .tracking:
return Constants.showCellHeight
case .searching, .trending:
if indexPath.row == temporaryDataSource.temporaryShows.count {
return Constants.loadingCellHeight
} else {
return Constants.showCellHeight
}
}
}
}
// MARK: - ShowTrackingInitiator
extension MainViewController: ShowTrackingInitiator {
func initiateTracking(of show: Show, sender: Any?) {
assert(!showTracker.isTracking(show))
showTracker.track(show) { success in
switch self.state {
case .searching, .trending:
self.updateCellAndDetailVC(for: show)
case .tracking:
self.updateTable()
}
}
// Update tracking activity indicators
(sender as? ShowTableViewCell)?.configure(with: show, animated: true)
if let selectedCell = temporaryShowCellAssociatedToSameShowAsThePresentedShowDetailViewController() {
selectedCell.configure(with: show, animated: false)
}
}
func initiateStopTracking(of show: Show, sender: Any?) {
assert(showTracker.isTracking(show))
showTracker.stopTracking(show) { result in
switch result {
case .success(let newShow):
// Initiator is the detail vc
if let detailVC = self.presentedShowDetailViewController {
switch self.state {
// Go back to tracked shows list, corresponding tracked show cell will be removed in viewDidAppear()
case .tracking:
_ = self.navigationController?.popViewController(animated: true)
// Update the detail vc
case .searching, .trending:
detailVC.configure(with: newShow, animated: true)
// The show is still in the search results
if let indexPath = self.temporaryDataSource.indexPath(ofFirstInvalidOrTemporaryShow: newShow) {
self.temporaryDataSource.updateTemporaryShow(at: indexPath, with: newShow)
if let cell = self.tableView.cellForRow(at: indexPath) as? SearchShowTableViewCell {
cell.configure(with: newShow, animated: true)
}
} else {
// The show no longer in search results because an ongoing search discarded it, do nothing
}
}
}
// Initiator is a tracked cell
else if let trackedCellIndexPath = sender as? IndexPath {
self.deleteRow(at: trackedCellIndexPath)
}
else {
assertionFailure()
}
case .failure(_):
// Hides "Stop Tracking" row action
if self.tableView.isEditing {
self.tableView.setEditing(false, animated: true)
}
}
}
}
}
// MARK: - Helpers
private extension MainViewController {
/// Removes a row in the table view, making other UI changes when proper, like removing empty sections or updating the custom table pages.
func deleteRow(at indexPath: IndexPath) {
if tableView.numberOfRows(inSection: indexPath.section) == 1 {
tableView.deleteSections([indexPath.section], with: .fade)
} else {
tableView.deleteRows(at: [indexPath], with: .fade)
}
delay(Constants.rowAnimationsDuration) { // Wait until animation ends so the table view's content size is up to date
self.updateTablePages()
self.updateNoContentLabels()
}
}
/// Updates the search bar and done button UI.
/// - parameter newState: If specified, the updates will be made as if the current state was the `newState`. Use this if you need to update the UI before the actual state changes.
func updateSearchUI(forNewState newState: State? = nil) {
switch newState ?? state {
case .searching, .trending:
searchBarTrailingConstraint.constant = -16 + doneButton.frame.width + searchBarToDoneButtonHorizontalConstraint.constant * 2 + 10
doneButton.isHidden = false
case .tracking:
searchBarTrailingConstraint.constant = -16
doneButton.isHidden = true
searchBar.text = nil
}
UIView.animate(withDuration: Constants.searchBarBeginEditingAnimationDuration,
delay: 0, usingSpringWithDamping: 1, initialSpringVelocity: 0,
options: .curveEaseInOut,
animations: { self.view.layoutIfNeeded() },
completion: nil)
}
/// Shows no content labels if table is empty when `state` is tracking, otherwise hides them.
func updateNoContentLabels() {
switch state {
case .tracking: noContentLabels.forEach { $0.isHidden = tableView.numberOfSections != 0 }
case .searching, .trending: noContentLabels.forEach { $0.isHidden = true }
}
}
/// Shows/hides "No Results", "No Connection" and other error messages if proper.
func updateSearchErrorLabel(with error: Show.FetchError? = nil) {
switch state {
case .tracking, .trending: noResultsLabel.isHidden = true
case .searching:
noResultsLabel.isHidden = searchController.isSearching || !temporaryDataSource.temporaryShows.isEmpty || searchBar.text == nil || searchBar.text == ""
switch error {
case .noConnection?, .serverFailure?, .persistenceFailure?: noResultsLabel.text = error!.description
case .unknown?: noResultsLabel.text = "Error"
case nil: noResultsLabel.text = "No Results"
}
}
}
/// Calls `configure(with:)` on the cell and detail view controller associated to the given show.
func updateCellAndDetailVC(for show: Show) {
// Update cell
switch state {
case .searching, .trending:
if let indexPath = temporaryDataSource.indexPath(ofFirstInvalidOrTemporaryShow: show) {
if let cell = self.tableView.cellForRow(at: indexPath) as? ShowTableViewCell,
cell.show?.isInvalidated == true || cell.show == show {
cell.configure(with: show, animated: true)
}
else {} // Cell might not be shown in the table just yet
} else {} // Show no longer in search results
case .tracking:
break // TODO: Implement
}
// Update detail vc
if let detailVC = presentedShowDetailViewController, detailVC.show == show {
detailVC.configure(with: show, animated: true)
}
}
/// Fades the whole table to white.
/// Make sure when the animation completes the table is empty, otherwise the effect won't look good.
func fadeTableToWhite(completion: (()->())? = nil) {
UIView.animate(withDuration: 0.25, animations: {
self.tableView.alpha = 0
}, completion: { _ in
self.tableView.alpha = 1
completion?()
})
}
func temporaryShowCellAssociatedToSameShowAsThePresentedShowDetailViewController() -> SearchShowTableViewCell? {
if let show = presentedShowDetailViewController?.show,
let indexPath = self.temporaryDataSource.indexPath(ofFirstInvalidOrTemporaryShow: show),
let cell = self.tableView.cellForRow(at: indexPath) as? SearchShowTableViewCell {
return cell
}
return nil
}
}
| gpl-3.0 | 0c062371f9b93aa403573aa223e159e5 | 39.986799 | 194 | 0.61724 | 5.479373 | false | false | false | false |
rowungiles/SwiftTech | SwiftTech/SwiftTech/Utilities/Operations/GetRestaurantsOperation.swift | 1 | 1851 | //
// GetRestaurants.swift
// SwiftTech
//
// Created by Rowun Giles on 08/01/2016.
// Copyright © 2016 Rowun Giles. All rights reserved.
//
import Foundation
protocol GetRestaurantsOperationDelegate: class {
func restaurantsFetched(restaurants: [RestaurantStruct], outcode: String)
func restaurantsFailedToFetched(outcode: String)
}
final class GetRestaurantsOperation : ConcurrentOperation {
weak var delegate: GetRestaurantsOperationDelegate?
private let networking = OutcodeRestaurantsNetworking()
private let outcode: String
init(outcode: String) {
self.outcode = outcode
super.init()
}
override func main() {
networking.fetchDataForOutcode(outcode, completion: { [weak self] (result) -> Void in
self?.modelDataFetched(result)
})
}
private func modelDataFetched(result: NetworkingResult) {
// todo: explore alternative to communicate failure, empty array doesn't communicate reasons well (e.g. bad data, or no data).
var restaurants: [RestaurantStruct]?
switch (result) {
case let .Success(data):
restaurants = try? RestaurantParser.parseData(data)
break
case .Failure(_):
break
}
NSOperationQueue.mainQueue().addOperationWithBlock { [weak self, weak delegate = self.delegate, outcode = self.outcode] () -> Void in
if let parsedRestaurants = restaurants {
delegate?.restaurantsFetched(parsedRestaurants, outcode: outcode)
} else {
delegate?.restaurantsFailedToFetched(outcode)
}
self?.state = .Finished
}
}
} | gpl-3.0 | 638dc44585635d90e766a84b96288f7a | 27.045455 | 141 | 0.598378 | 5.362319 | false | false | false | false |
hermantai/samples | ios/SwiftUI-Cookbook-2nd-Edition/Chapter09-Driving-SwiftUI-with-data/05-Sharing-state-objects-to-multiple-views-using-@EnvironmentObject/SongPlayer/SongPlayer/ContentView.swift | 1 | 3529 | //
// ContentView.swift
// SongPlayer
//
// Created by Giordano Scalzo on 25/07/2021.
//
import SwiftUI
struct Song: Identifiable, Equatable {
var id = UUID()
let artist: String
let name: String
let cover: String
}
struct ContentView: View {
@EnvironmentObject
private var musicPlayer: MusicPlayer
private let songs = [
Song(artist: "Luke", name: "99", cover: "cover0"),
Song(artist: "Foxing", name: "No Trespassing", cover: "cover1"),
Song(artist: "Breaking Benjamin", name: "Phobia", cover: "cover2"),
Song(artist: "J2", name: "Solenoid", cover: "cover3"),
Song(artist: "Wildflower Clothing", name: "Lightning Bottles", cover: "cover4"),
Song(artist: "The Broken Spirits", name: "Rubble", cover: "cover5"),
]
var body: some View {
ZStack(alignment: .bottom) {
NavigationView {
List(self.songs) { song in
SongView(song: song)
}
.listStyle(.plain)
.navigationTitle("Music Player")
}
MiniPlayerView()
.background(.gray)
.offset(y: 44)
}
}
}
struct MiniPlayerView: View {
@EnvironmentObject
private var musicPlayer: MusicPlayer
var body: some View {
if let currentSong = musicPlayer.currentSong {
SongView(song: currentSong)
.padding(.all, 24)
} else {
/*@START_MENU_TOKEN@*/EmptyView()/*@END_MENU_TOKEN@*/
}
}
}
struct SongView: View {
@EnvironmentObject
private var musicPlayer: MusicPlayer
let song: Song
var body: some View {
HStack {
NavigationLink(destination: PlayerView(song: song)) {
Image(song.cover)
.renderingMode(.original)
.resizable()
.aspectRatio(contentMode: .fill)
.frame(width: 100, height: 100)
VStack(alignment: .leading) {
Text(song.name)
Text(song.artist).italic()
}
}
Spacer()
PlayButton(song: song)
}.buttonStyle(PlainButtonStyle())
}
}
struct PlayerView: View {
@EnvironmentObject
private var musicPlayer: MusicPlayer
let song: Song
var body: some View {
VStack {
Image(song.cover)
.renderingMode(.original)
.resizable()
.aspectRatio(contentMode: .fill)
.frame(width: 300, height: 300)
HStack {
Text(song.name)
Text(song.artist).italic()
}
PlayButton(song: song)
}
}
}
struct PlayButton: View {
@EnvironmentObject
private var musicPlayer: MusicPlayer
let song: Song
private var buttonText: String {
if song == musicPlayer.currentSong {
return "stop"
} else {
return "play"
}
}
var body: some View {
Button {
musicPlayer.pressButton(song: song)
} label: {
Image(systemName: buttonText)
.font(.system(.largeTitle))
.foregroundColor(.black)
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
.environmentObject(MusicPlayer())
}
}
| apache-2.0 | de8d5ee538e48e80e87e8725f11f0583 | 24.759124 | 88 | 0.519977 | 4.625164 | false | false | false | false |
yanagiba/swift-ast | Tests/ParserTests/Expression/Primary/ParserSuperclassExpressionTests.swift | 2 | 5327 | /*
Copyright 2016-2018 Ryuichi Intellectual Property and the Yanagiba project contributors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
import XCTest
@testable import AST
class ParserSuperclassExpressionTests: XCTestCase {
func testSuperclassMethodExpression() {
parseExpressionAndTest("super.foo", "super.foo", testClosure: { expr in
guard
let superExpr = expr as? SuperclassExpression,
case .method(let name) = superExpr.kind,
name.isSyntacticallyEqual(to: .name("foo"))
else {
XCTFail("Failed in getting a superclass expression")
return
}
})
}
func testSuperclassSubscriptExpression() {
parseExpressionAndTest("super[0]", "super[0]", testClosure: { expr in
guard let superExpr = expr as? SuperclassExpression,
case .subscript(let args) = superExpr.kind,
args.count == 1,
let literalExpr = args[0].expression as? LiteralExpression,
case .integer(let i, _) = literalExpr.kind,
i == 0
else {
XCTFail("Failed in getting a superclass expression")
return
}
XCTAssertNil(args[0].identifier)
})
}
func testSuperclassSubscriptExprWithExprList() {
parseExpressionAndTest("super[0, 1, 5]", "super[0, 1, 5]", testClosure: { expr in
guard let superExpr = expr as? SuperclassExpression,
case .subscript(let args) = superExpr.kind,
args.count == 3
else {
XCTFail("Failed in getting a superclass expression")
return
}
XCTAssertNil(args[0].identifier)
XCTAssertTrue(args[0].expression is LiteralExpression)
XCTAssertNil(args[1].identifier)
XCTAssertTrue(args[1].expression is LiteralExpression)
XCTAssertNil(args[2].identifier)
XCTAssertTrue(args[2].expression is LiteralExpression)
})
}
func testSuperclassSubscriptExprWithVariables() {
parseExpressionAndTest("super [ foo, 0, bar,1, 5 ] ", "super[foo, 0, bar, 1, 5]", testClosure: { expr in
guard let superExpr = expr as? SuperclassExpression,
case .subscript(let args) = superExpr.kind,
args.count == 5
else {
XCTFail("Failed in getting a superclass expression")
return
}
XCTAssertNil(args[0].identifier)
XCTAssertTrue(args[0].expression is IdentifierExpression)
XCTAssertNil(args[1].identifier)
XCTAssertTrue(args[1].expression is LiteralExpression)
XCTAssertNil(args[2].identifier)
XCTAssertTrue(args[2].expression is IdentifierExpression)
XCTAssertNil(args[3].identifier)
XCTAssertTrue(args[3].expression is LiteralExpression)
XCTAssertNil(args[4].identifier)
XCTAssertTrue(args[4].expression is LiteralExpression)
})
}
func testSuperclassSubscriptArgumentWithIdentifier() {
// https://github.com/yanagiba/swift-ast/issues/38
parseExpressionAndTest("super[bar: 0]", "super[bar: 0]", testClosure: { expr in
XCTAssertTrue(expr is SuperclassExpression)
})
parseExpressionAndTest("super[a: 0, b: 1, c: 2]", "super[a: 0, b: 1, c: 2]")
parseExpressionAndTest("super [bar: n+1]", "super[bar: n + 1]")
parseExpressionAndTest("super [bar: bar()]", "super[bar: bar()]")
parseExpressionAndTest("super [bar: try bar()]", "super[bar: try bar()]")
}
func testSuperclassInitializerExpression() {
parseExpressionAndTest("super.init", "super.init", testClosure: { expr in
guard let superExpr = expr as? SuperclassExpression,
case .initializer = superExpr.kind else {
XCTFail("Failed in getting a superclass expression")
return
}
})
}
func testArgumentListOnSameLine() {
parseExpressionAndTest("super\n[foo]", "", errorClosure: { error in
// :)
})
}
func testSourceRange() {
let testExprs: [(testString: String, expectedEndColumn: Int)] = [
("super.foo", 10),
("super.init", 11),
("super[foo]", 11),
]
for t in testExprs {
parseExpressionAndTest(t.testString, t.testString, testClosure: { expr in
XCTAssertEqual(expr.sourceRange, getRange(1, 1, 1, t.expectedEndColumn))
})
}
}
static var allTests = [
("testSuperclassMethodExpression", testSuperclassMethodExpression),
("testSuperclassSubscriptExpression", testSuperclassSubscriptExpression),
("testSuperclassSubscriptExprWithExprList", testSuperclassSubscriptExprWithExprList),
("testSuperclassSubscriptExprWithVariables", testSuperclassSubscriptExprWithVariables),
("testSuperclassSubscriptArgumentWithIdentifier", testSuperclassSubscriptArgumentWithIdentifier),
("testSuperclassInitializerExpression", testSuperclassInitializerExpression),
("testArgumentListOnSameLine", testArgumentListOnSameLine),
("testSourceRange", testSourceRange),
]
}
| apache-2.0 | 88221fc79a2d801fc2ab90338b5ce2b4 | 36.251748 | 110 | 0.689506 | 4.564696 | false | true | false | false |
Hoodps/Swift-Tutorial | swiftPage/swiftPage/AppDelegate.swift | 1 | 2584 | //
// AppDelegate.swift
// swiftPage
//
// Created by xiexz on 15/12/19.
// Copyright © 2015年 xiexz. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
self.window = UIWindow(frame: UIScreen.mainScreen().bounds)
let pageViewController: PagingNavController = PagingNavController()
let navigationController: UINavigationController = UINavigationController(rootViewController: pageViewController)
self.window?.rootViewController = navigationController
self.window?.backgroundColor = UIColor.whiteColor()
self.window?.makeKeyAndVisible()
return true
}
func applicationWillResignActive(application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
| apache-2.0 | 8ff89fa252c1d7ae064fccdd7385235b | 46.796296 | 285 | 0.748935 | 5.697572 | false | false | false | false |
cpmpercussion/microjam | Pods/Avatar/Avatar/Avatar.swift | 2 | 3840 | //
// Avatar.swift
// Avatar
//
// Created by William Vabrinskas on 6/13/17.
// Copyright © 2017 williamvabrinskas. All rights reserved.
//
import Foundation
import CoreGraphics
import CoreImage
import UIKit
typealias Colors = (primary: UIColor, secondary: UIColor, tertiary: UIColor)
open class Avatar {
private class func getRandomColor() -> UIColor {
let red = CGFloat(arc4random_uniform(256)) / 255.0
let green = CGFloat(arc4random_uniform(256)) / 255.0
let blue = CGFloat(arc4random_uniform(256)) / 255.0
return UIColor(red: red, green: green, blue: blue, alpha: 1.0)
}
private class func colors() -> Colors {
let colors:Colors = (primary: getRandomColor(), secondary: getRandomColor(), tertiary: getRandomColor())
return colors
}
private class func getImageMap(length: Int) -> [Int] {
var map = [Int]()
for _ in 0..<length {
map.append(Int(arc4random_uniform(3)))
}
return map
}
public static var customSeed:AvatarSeed?
open class func generate(seed: AvatarSeed) -> UIImage? {
customSeed = seed
return generate(for: seed.size, scale: seed.scale)
}
open class func generate(for size: CGSize, scale: Int? , complete:@escaping (_ seed: AvatarSeed, _ image:UIImage?) -> ()) {
let width = Int(customSeed?.size.width ?? size.width)
let height = Int(customSeed?.size.height ?? size.height)
let pixelSize = scale ?? 20
let totalColumns = width / pixelSize
let totalRows = height / pixelSize
let wRemainder = width % pixelSize
let hRemainder = height % pixelSize
// if #available(iOS 11, *) {
// let wRemainder = width.dividedReportingOverflow(by: pixelSize).partialValue
// let hRemainder = height.dividedReportingOverflow(by: pixelSize).partialValue
// }
let mapValues = customSeed?.map ?? getImageMap(length: totalColumns * totalRows)
let colors = customSeed?.colors ?? Avatar.colors()
var x = 0 //columns counter
var y = 0 //rows counter
UIGraphicsBeginImageContextWithOptions(size, true, 1)
let context = UIGraphicsGetCurrentContext()!
for position in 0..<mapValues.count {
//context stuff
let colorIndex = mapValues[position]
var color = UIColor.black
switch colorIndex {
case 0:
color = colors.primary
case 1:
color = colors.secondary
case 2:
color = colors.tertiary
default:
color = .black
}
context.setFillColor(color.cgColor)
context.fill(CGRect(x: CGFloat(x * pixelSize), y:CGFloat(y * pixelSize), width:CGFloat(pixelSize + (pixelSize * wRemainder)), height:CGFloat(pixelSize + (pixelSize * hRemainder))));
x = x + 1
if x == totalColumns {
x = 0
y = y + 1
}
}
let outputImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext()
let seed = AvatarSeed(map: mapValues, colors: colors, size: size, scale:pixelSize)
complete(seed, outputImage)
}
open class func generate(for size: CGSize, scale: Int?) -> UIImage? {
var outputImage: UIImage?
self.generate(for: size, scale: scale) { (seed, image) in
outputImage = image
}
return outputImage
}
}
| mit | 860c509cd1e3833985331b29d6f612a8 | 29.228346 | 193 | 0.554832 | 4.871827 | false | false | false | false |
mitochrome/complex-gestures-demo | apps/GestureRecognizer/Carthage/Checkouts/RxSwift/RxSwift/Rx.swift | 55 | 6206 | //
// Rx.swift
// RxSwift
//
// Created by Krunoslav Zaher on 2/14/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
#if TRACE_RESOURCES
fileprivate var resourceCount: AtomicInt = 0
/// Resource utilization information
public struct Resources {
/// Counts internal Rx resource allocations (Observables, Observers, Disposables, etc.). This provides a simple way to detect leaks during development.
public static var total: Int32 {
return resourceCount.valueSnapshot()
}
/// Increments `Resources.total` resource count.
///
/// - returns: New resource count
public static func incrementTotal() -> Int32 {
return AtomicIncrement(&resourceCount)
}
/// Decrements `Resources.total` resource count
///
/// - returns: New resource count
public static func decrementTotal() -> Int32 {
return AtomicDecrement(&resourceCount)
}
}
#endif
/// Swift does not implement abstract methods. This method is used as a runtime check to ensure that methods which intended to be abstract (i.e., they should be implemented in subclasses) are not called directly on the superclass.
func rxAbstractMethod(file: StaticString = #file, line: UInt = #line) -> Swift.Never {
rxFatalError("Abstract method", file: file, line: line)
}
func rxFatalError(_ lastMessage: @autoclosure () -> String, file: StaticString = #file, line: UInt = #line) -> Swift.Never {
// The temptation to comment this line is great, but please don't, it's for your own good. The choice is yours.
fatalError(lastMessage(), file: file, line: line)
}
func rxFatalErrorInDebug(_ lastMessage: @autoclosure () -> String, file: StaticString = #file, line: UInt = #line) {
#if DEBUG
fatalError(lastMessage(), file: file, line: line)
#else
print("\(file):\(line): \(lastMessage())")
#endif
}
func incrementChecked(_ i: inout Int) throws -> Int {
if i == Int.max {
throw RxError.overflow
}
defer { i += 1 }
return i
}
func decrementChecked(_ i: inout Int) throws -> Int {
if i == Int.min {
throw RxError.overflow
}
defer { i -= 1 }
return i
}
#if DEBUG
import class Foundation.Thread
final class SynchronizationTracker {
private let _lock = RecursiveLock()
public enum SychronizationErrorMessages: String {
case variable = "Two different threads are trying to assign the same `Variable.value` unsynchronized.\n This is undefined behavior because the end result (variable value) is nondeterministic and depends on the \n operating system thread scheduler. This will cause random behavior of your program.\n"
case `default` = "Two different unsynchronized threads are trying to send some event simultaneously.\n This is undefined behavior because the ordering of the effects caused by these events is nondeterministic and depends on the \n operating system thread scheduler. This will result in a random behavior of your program.\n"
}
private var _threads = Dictionary<UnsafeMutableRawPointer, Int>()
private func synchronizationError(_ message: String) {
#if FATAL_SYNCHRONIZATION
rxFatalError(message)
#else
print(message)
#endif
}
func register(synchronizationErrorMessage: SychronizationErrorMessages) {
_lock.lock(); defer { _lock.unlock() }
let pointer = Unmanaged.passUnretained(Thread.current).toOpaque()
let count = (_threads[pointer] ?? 0) + 1
if count > 1 {
synchronizationError(
"⚠️ Reentrancy anomaly was detected. ⚠️\n" +
" > Debugging: To debug this issue you can set a breakpoint in \(#file):\(#line) and observe the call stack.\n" +
" > Problem: This behavior is breaking the observable sequence grammar. `next (error | completed)?`\n" +
" This behavior breaks the grammar because there is overlapping between sequence events.\n" +
" Observable sequence is trying to send an event before sending of previous event has finished.\n" +
" > Interpretation: This could mean that there is some kind of unexpected cyclic dependency in your code,\n" +
" or that the system is not behaving in the expected way.\n" +
" > Remedy: If this is the expected behavior this message can be suppressed by adding `.observeOn(MainScheduler.asyncInstance)`\n" +
" or by enqueing sequence events in some other way.\n"
)
}
_threads[pointer] = count
if _threads.count > 1 {
synchronizationError(
"⚠️ Synchronization anomaly was detected. ⚠️\n" +
" > Debugging: To debug this issue you can set a breakpoint in \(#file):\(#line) and observe the call stack.\n" +
" > Problem: This behavior is breaking the observable sequence grammar. `next (error | completed)?`\n" +
" This behavior breaks the grammar because there is overlapping between sequence events.\n" +
" Observable sequence is trying to send an event before sending of previous event has finished.\n" +
" > Interpretation: " + synchronizationErrorMessage.rawValue +
" > Remedy: If this is the expected behavior this message can be suppressed by adding `.observeOn(MainScheduler.asyncInstance)`\n" +
" or by synchronizing sequence events in some other way.\n"
)
}
}
func unregister() {
_lock.lock(); defer { _lock.unlock() }
let pointer = Unmanaged.passUnretained(Thread.current).toOpaque()
_threads[pointer] = (_threads[pointer] ?? 1) - 1
if _threads[pointer] == 0 {
_threads[pointer] = nil
}
}
}
#endif
| mit | 07358510c029fe6cf9634aa343053566 | 45.186567 | 341 | 0.615608 | 4.835156 | false | false | false | false |
raptorxcz/Rubicon | Generator/Generator/CreateStubInteractor.swift | 1 | 8554 | //
// CreateStubInteractor.swift
// Generator
//
// Created by Kryštof Matěj on 16/02/2019.
// Copyright © 2019 Kryštof Matěj. All rights reserved.
//
public final class CreateStubInteractor: CreateMockInteractor {
private let accessLevel: AccessLevel
private var protocolType: ProtocolType?
public init(accessLevel: AccessLevel) {
self.accessLevel = accessLevel
}
public func generate(from protocolType: ProtocolType) -> String {
self.protocolType = protocolType
var result = [String]()
result.append("\(accessLevel.makeClassString())final class \(protocolType.name)Stub: \(protocolType.name) {")
result += generateBody(from: protocolType)
result.append("}")
var string = result.joined(separator: "\n")
if !string.isEmpty {
string.append("\n")
}
return string
}
private func generateBody(from protocolType: ProtocolType) -> [String] {
var content = [String]()
if let throwSampleError = makeThrowSampleError(for: protocolType) {
content.append("")
content.append(throwSampleError)
}
if !protocolType.variables.isEmpty {
content.append("")
content += generateVariables(protocolType.variables)
}
let stubVariables = generateStubVariables(for: protocolType.functions)
if !stubVariables.isEmpty {
content.append("")
content += stubVariables
}
let initRows = generateInit(for: protocolType)
if !initRows.isEmpty {
content.append("")
content += initRows
}
let body = generateFunctionsBody(for: protocolType)
if !body.isEmpty {
content.append("")
content += body
}
return content
}
private func generateFunctionsBody(for protocolType: ProtocolType) -> [String] {
var rows = [[String]]()
for function in protocolType.functions {
rows.append(generateStub(of: function))
}
return rows.joined(separator: [""]).compactMap({ $0 })
}
private func makeThrowSampleError(for type: ProtocolType) -> String? {
let isAnyFuncThrowing = type.functions.contains(where: { $0.isThrowing })
if isAnyFuncThrowing {
return """
\t\(accessLevel.makeContentString())enum StubError: Error {
\t\tcase stubError
\t}
\t\(accessLevel.makeContentString())typealias ThrowBlock = () throws -> Void
"""
} else {
return nil
}
}
private func generateInit(for type: ProtocolType) -> [String] {
var variables = type.variables.compactMap(makeArgument(from:))
variables += type.functions.compactMap(makeReturnArgument(of:))
let arguments = variables.joined(separator: ", ")
guard !arguments.isEmpty || accessLevel == .public else {
return []
}
var bodyRows = type.variables.compactMap(makeAssigment(of:))
bodyRows += type.functions.compactMap(makeReturnAssigment(of:))
var result = [String]()
result.append("\t\(accessLevel.makeContentString())init(\(arguments)) {")
result += bodyRows
result.append("\t}")
return result
}
private func makeArgument(from variable: VarDeclarationType) -> String? {
if variable.type.isOptional {
return nil
} else {
let typeString = TypeStringFactory.makeInitString(variable.type)
return "\(variable.identifier): \(typeString)"
}
}
private func makeAssigment(of variable: VarDeclarationType) -> String? {
if variable.type.isOptional {
return nil
} else {
return "\t\tself.\(variable.identifier) = \(variable.identifier)"
}
}
private func makeReturnArgument(of function: FunctionDeclarationType) -> String? {
guard let returnType = function.returnType, !returnType.isOptional else {
return nil
}
let functionName = getName(from: function)
let typeString = TypeStringFactory.makeInitString(returnType)
return "\(functionName)Return: \(typeString)"
}
private func makeReturnAssigment(of function: FunctionDeclarationType) -> String? {
guard let returnType = function.returnType, !returnType.isOptional else {
return nil
}
let functionName = getName(from: function)
return "\t\tself.\(functionName)Return = \(functionName)Return"
}
private func generateVariables(_ variables: [VarDeclarationType]) -> [String] {
var result = [String]()
for variable in variables {
let typeString = TypeStringFactory.makeSimpleString(variable.type)
result.append("\t\(accessLevel.makeContentString())var \(variable.identifier): \(typeString)")
}
return result
}
private func generateStubVariables(for functions: [FunctionDeclarationType]) -> [String] {
var result = [String]()
for function in functions {
result += generateFunctionVariables(function)
}
return result
}
private func generateFunctionVariables(_ function: FunctionDeclarationType) -> [String] {
let functionName = getName(from: function)
var results = [String]()
if function.isThrowing {
results.append("\t\(accessLevel.makeContentString())var \(functionName)ThrowBlock: ThrowBlock?")
}
if let returnType = function.returnType {
let returnTypeString = TypeStringFactory.makeSimpleString(returnType)
results.append("\t\(accessLevel.makeContentString())var \(functionName)Return: \(returnTypeString)")
}
return results
}
private func getName(from function: FunctionDeclarationType) -> String {
let argumentsTitles = function.arguments.map(getArgumentName(from:)).joined()
let arguments = isFunctionNameUnique(function) ? argumentsTitles : ""
return "\(function.name)\(arguments)"
}
private func getArgumentName(from type: ArgumentType) -> String {
if let label = type.label, label != "_" {
return label.capitalizingFirstLetter()
} else {
return type.name.capitalizingFirstLetter()
}
}
private func isFunctionNameUnique(_ function: FunctionDeclarationType) -> Bool {
guard let protocolType = protocolType else {
return false
}
var matchCount = 0
for fc in protocolType.functions {
if fc.name == function.name {
matchCount += 1
}
}
return matchCount > 1
}
private func generateArgument(_ argument: ArgumentType) -> String {
let labelString: String
if let label = argument.label {
labelString = "\(label) "
} else {
labelString = ""
}
let typeString = TypeStringFactory.makeFunctionArgumentString(argument.type)
return "\(labelString)\(argument.name): \(typeString)"
}
private func generateStub(of function: FunctionDeclarationType) -> [String] {
let functionName = getName(from: function)
var functionBody = [String]()
if function.isThrowing {
functionBody.append("try \(functionName)ThrowBlock?()")
}
if function.returnType != nil {
functionBody.append("return \(functionName)Return")
}
return makeFunctionDefinition(of: function, body: functionBody)
}
private func makeFunctionDefinition(of function: FunctionDeclarationType, body: [String]) -> [String] {
var result = [String]()
let argumentsString = function.arguments.map(generateArgument).joined(separator: ", ")
var returnString = ""
if function.isAsync {
returnString += "async "
}
if function.isThrowing {
returnString += "throws "
}
if let returnType = function.returnType {
let returnTypeString = TypeStringFactory.makeSimpleString(returnType)
returnString += "-> \(returnTypeString) "
}
result.append("\t\(accessLevel.makeContentString())func \(function.name)(\(argumentsString)) \(returnString){")
result += body.map({ "\t\t\($0)" })
result.append("\t}")
return result
}
}
| mit | 283930738c890879eaa7fad6bb5929c6 | 31.505703 | 119 | 0.612703 | 5.019965 | false | false | false | false |
WeMadeCode/ZXPageView | Example/Pods/SwifterSwift/Sources/SwifterSwift/CoreGraphics/CGVectorExtensions.swift | 1 | 3287 | //
// CGVectorExtensions.swift
// SwifterSwift
//
// Created by Robbie Moyer on 7/25/18.
// Copyright © 2018 SwifterSwift
//
#if canImport(CoreGraphics)
import CoreGraphics
// MARK: - Properties
public extension CGVector {
/// SwifterSwift: The angle of rotation (in radians) of the vector.
/// The range of the angle is -π to π; an angle of 0 points to the right.
///
/// https://en.wikipedia.org/wiki/Atan2
var angle: CGFloat {
return atan2(dy, dx)
}
/// SwifterSwift: The magnitude (or length) of the vector.
///
/// https://en.wikipedia.org/wiki/Euclidean_vector#Length
var magnitude: CGFloat {
return sqrt((dx * dx) + (dy * dy))
}
}
// MARK: - Initializers
public extension CGVector {
/// SwifterSwift: Creates a vector with the given magnitude and angle.
///
/// https://www.grc.nasa.gov/WWW/K-12/airplane/vectpart.html
///
/// let vector = CGVector(angle: .pi, magnitude: 1)
///
/// - Parameters:
/// - angle: The angle of rotation (in radians) counterclockwise from the positive x-axis.
/// - magnitude: The lenth of the vector.
///
init(angle: CGFloat, magnitude: CGFloat) {
self.init(dx: magnitude * cos(angle), dy: magnitude * sin(angle))
}
}
// MARK: - Operators
public extension CGVector {
/// SwifterSwift: Multiplies a scalar and a vector (commutative).
///
/// let vector = CGVector(dx: 1, dy: 1)
/// let largerVector = vector * 2
///
/// - Parameters:
/// - vector: The vector to be multiplied
/// - scalar: The scale by which the vector will be multiplied
/// - Returns: The vector with its magnitude scaled
static func * (vector: CGVector, scalar: CGFloat) -> CGVector {
return CGVector(dx: vector.dx * scalar, dy: vector.dy * scalar)
}
/// SwifterSwift: Multiplies a scalar and a vector (commutative).
///
/// let vector = CGVector(dx: 1, dy: 1)
/// let largerVector = 2 * vector
///
/// - Parameters:
/// - scalar: The scalar by which the vector will be multiplied
/// - vector: The vector to be multiplied
/// - Returns: The vector with its magnitude scaled
static func * (scalar: CGFloat, vector: CGVector) -> CGVector {
return CGVector(dx: scalar * vector.dx, dy: scalar * vector.dy)
}
/// SwifterSwift: Compound assignment operator for vector-scalr multiplication
///
/// var vector = CGVector(dx: 1, dy: 1)
/// vector *= 2
///
/// - Parameters:
/// - vector: The vector to be multiplied
/// - scalar: The scale by which the vector will be multiplied
static func *= (vector: inout CGVector, scalar: CGFloat) {
// swiftlint:disable:next shorthand_operator
vector = vector * scalar
}
/// SwifterSwift: Negates the vector. The direction is reversed, but magnitude
/// remains the same.
///
/// let vector = CGVector(dx: 1, dy: 1)
/// let reversedVector = -vector
///
/// - Parameter vector: The vector to be negated
/// - Returns: The negated vector
static prefix func - (vector: CGVector) -> CGVector {
return CGVector(dx: -vector.dx, dy: -vector.dy)
}
}
#endif
| mit | c47bae8caacc8da33d0b24731311114d | 29.691589 | 98 | 0.606882 | 3.995134 | false | false | false | false |
Neku/easy-hodl | ios/CryptoSaver/CryptoSaver/SettingsViewController.swift | 1 | 3020 | //
// SettingsViewController.swift
// CryptoSaver
//
// Created by Simone D'Amico on 16/08/2017.
// Copyright © 2017 Simone D'Amico. All rights reserved.
//
import UIKit
import AVFoundation
import QRCodeReader
class SettingsViewController: UIViewController, QRCodeReaderViewControllerDelegate {
lazy var readerVC: QRCodeReaderViewController = {
let builder = QRCodeReaderViewControllerBuilder {
$0.reader = QRCodeReader(metadataObjectTypes: [AVMetadataObjectTypeQRCode], captureDevicePosition: .back)
}
return QRCodeReaderViewController(builder: builder)
}()
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.
}
@IBAction func scanKrakenQR() {
// Retrieve the QRCode content
// By using the delegate pattern
readerVC.delegate = self
// Or by using the closure pattern
readerVC.completionBlock = { (result: QRCodeReaderResult?) in
let krakenURL = URL(string: result!.value)!
let krakenKey = krakenURL.queryItems["key"]!
let krakenSecret = krakenURL.queryItems["secret"]!
EasyHodlAPI.setKrakenKeys(key: krakenKey, secret: krakenSecret){
let alert = UIAlertController(title: "You're all done", message: "Your kraken account is now linked", preferredStyle: UIAlertControllerStyle.alert)
alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.default, handler: nil))
self.present(alert, animated: true, completion: nil)
}
}
// Presents the readerVC as modal form sheet
readerVC.modalPresentationStyle = .formSheet
present(readerVC, animated: true, completion: nil)
}
@IBAction func logout() {
EasyHodlAPI.logout()
let appDelegate = UIApplication.shared.delegate as! AppDelegate
appDelegate.checkLogin()
}
// MARK: - QRCodeReaderViewController Delegate Methods
func reader(_ reader: QRCodeReaderViewController, didScanResult result: QRCodeReaderResult) {
reader.stopScanning()
dismiss(animated: true, completion: nil)
}
//This is an optional delegate method, that allows you to be notified when the user switches the cameraName
//By pressing on the switch camera button
func reader(_ reader: QRCodeReaderViewController, didSwitchCamera newCaptureDevice: AVCaptureDeviceInput) {
if let cameraName = newCaptureDevice.device.localizedName {
print("Switching capturing to: \(cameraName)")
}
}
func readerDidCancel(_ reader: QRCodeReaderViewController) {
reader.stopScanning()
dismiss(animated: true, completion: nil)
}
}
| mit | 8f5397f3ab8a78d54698bc742b00d712 | 34.517647 | 163 | 0.665452 | 5.134354 | false | false | false | false |
WildDogTeam/demo-ios-officemover | OfficeMover5000/ChangeBackgroundController.swift | 1 | 1735 | //
// ChangeBackgroundController.swift
// OfficeMover500
//
// Created by Garin on 11/2/15.
// Copyright (c) 2015 Wilddog. All rights reserved.
//
import UIKit
class ChangeBackgroundController : PopoverMenuController {
override var numItems: Int { return Floors.count }
override func viewDidLoad() {
super.viewDidLoad()
// Adding a gutter to the menu
tableView.contentInset = UIEdgeInsetsMake(15, 0, 15, 15);
preferredContentSize.height += 30
}
// Set the cell with an image and the text
override func populateCell(cell: PopoverMenuItemCell, row: Int) {
cell.textLabel?.text = Floors[row].0
cell.name = Floors[row].1
let imageName = Floors[row].1
if let image = UIImage(named: "\(imageName)_unselected.png") {
cell.imageView?.image = image
} else {
// Create blank image ths size of wood
if let woodImage = UIImage(named: "wood_unselected.png") {
UIGraphicsBeginImageContextWithOptions(woodImage.size, false, 0.0)
let blankImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
cell.imageView?.image = blankImage
}
}
}
// When selected, add an item using the delegate, and dismiss the popover
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
let type = Floors[indexPath.row].1
// Set background on Wilddog
delegate?.setBackground?(type)
// Actually change background locally
delegate?.setBackgroundLocally(type)
dismissPopover(true)
}
} | mit | df8c9e9d8be15ee24fb7824e92605dc4 | 32.384615 | 101 | 0.629971 | 4.887324 | false | false | false | false |
Yalantis/PixPic | PixPic/Classes/Flow/Misc/FollowerViewCell.swift | 1 | 836 | //
// FollowerViewCell.swift
// PixPic
//
// Created by anna on 3/3/16.
// Copyright © 2016 Yalantis. All rights reserved.
//
import UIKit
class FollowerViewCell: UITableViewCell, CellInterface {
@IBOutlet private weak var profileImageView: UIImageView!
@IBOutlet private weak var profileLabel: UILabel!
func configure(withFollower follower: User) {
profileLabel.text = follower.username ?? ""
profileImageView.layer.cornerRadius = profileImageView.frame.size.width / 2
if let avatar = follower.avatar?.url, url = NSURL(string: avatar) {
profileImageView.kf_setImageWithURL(
url,
placeholderImage: UIImage.avatarPlaceholderImage
)
} else {
profileImageView.image = UIImage.avatarPlaceholderImage
}
}
}
| mit | b23c483e9a4599364f0b5aca40286b65 | 27.793103 | 83 | 0.658683 | 4.771429 | false | false | false | false |
shaymanjohn/speccyMac | speccyMac/GameSelectViewController.swift | 1 | 1340 | //
// GameSelectViewController.swift
// speccyMac
//
// Created by John Ward on 18/08/2017.
// Copyright © 2017 John Ward. All rights reserved.
//
import Cocoa
class GameSelectViewController: NSViewController {
weak var machine: Machine!
var sortedGames: [Game] = []
override func viewDidLoad() {
super.viewDidLoad()
sortedGames = machine.games.sorted(by: { (game1 : Game, game2 : Game) -> Bool in
return game1.name < game2.name
})
}
}
extension GameSelectViewController: NSTableViewDataSource {
func numberOfRows(in tableView: NSTableView) -> Int {
return sortedGames.count
}
}
extension GameSelectViewController: NSTableViewDelegate {
func tableView(_ tableView: NSTableView, viewFor tableColumn: NSTableColumn?, row: Int) -> NSView? {
let game = sortedGames[row]
let tf = NSTextField(labelWithString: game.name)
return tf
}
func tableViewSelectionDidChange(_ notification: Notification) {
if let tv = notification.object as? NSTableView {
if tv.selectedRow >= 0 {
let selectedGame = sortedGames[tv.selectedRow]
machine.loadGame(selectedGame.file)
dismiss(self)
}
}
}
}
| gpl-3.0 | 5047e65496398d3ebf1119358ed3127a | 25.78 | 104 | 0.61165 | 4.799283 | false | false | false | false |
stephentyrone/swift | test/Sema/struct_equatable_hashable.swift | 4 | 13464 | // RUN: %target-swift-frontend -typecheck -verify -primary-file %s %S/Inputs/struct_equatable_hashable_other.swift -verify-ignore-unknown -swift-version 4
var hasher = Hasher()
struct Point: Hashable {
let x: Int
let y: Int
}
func point() {
if Point(x: 1, y: 2) == Point(x: 2, y: 1) { }
let _: Int = Point(x: 3, y: 5).hashValue
Point(x: 3, y: 5).hash(into: &hasher)
Point(x: 1, y: 2) == Point(x: 2, y: 1) // expected-warning {{result of operator '==' is unused}}
}
struct Pair<T: Hashable>: Hashable {
let first: T
let second: T
func same() -> Bool {
return first == second
}
}
func pair() {
let p1 = Pair(first: "a", second: "b")
let p2 = Pair(first: "a", second: "c")
if p1 == p2 { }
let _: Int = p1.hashValue
p1.hash(into: &hasher)
}
func localStruct() -> Bool {
struct Local: Equatable {
let v: Int
}
return Local(v: 5) == Local(v: 4)
}
//------------------------------------------------------------------------------
// Verify compiler can derive hash(into:) implementation from hashValue
struct CustomHashValue: Hashable {
let x: Int
let y: Int
static func ==(x: CustomHashValue, y: CustomHashValue) -> Bool { return true }
func hash(into hasher: inout Hasher) {}
}
func customHashValue() {
if CustomHashValue(x: 1, y: 2) == CustomHashValue(x: 2, y: 3) { }
let _: Int = CustomHashValue(x: 1, y: 2).hashValue
CustomHashValue(x: 1, y: 2).hash(into: &hasher)
}
//------------------------------------------------------------------------------
// Verify compiler can derive hashValue implementation from hash(into:)
struct CustomHashInto: Hashable {
let x: Int
let y: Int
func hash(into hasher: inout Hasher) {
hasher.combine(x)
hasher.combine(y)
}
static func ==(x: CustomHashInto, y: CustomHashInto) -> Bool { return true }
}
func customHashInto() {
if CustomHashInto(x: 1, y: 2) == CustomHashInto(x: 2, y: 3) { }
let _: Int = CustomHashInto(x: 1, y: 2).hashValue
CustomHashInto(x: 1, y: 2).hash(into: &hasher)
}
// Check use of an struct's synthesized members before the struct is actually declared.
struct UseStructBeforeDeclaration {
let eqValue = StructToUseBeforeDeclaration(v: 4) == StructToUseBeforeDeclaration(v: 5)
let hashValue = StructToUseBeforeDeclaration(v: 1).hashValue
let hashInto: (inout Hasher) -> Void = StructToUseBeforeDeclaration(v: 1).hash(into:)
}
struct StructToUseBeforeDeclaration: Hashable {
let v: Int
}
func getFromOtherFile() -> AlsoFromOtherFile { return AlsoFromOtherFile(v: 4) }
func overloadFromOtherFile() -> YetAnotherFromOtherFile { return YetAnotherFromOtherFile(v: 1.2) }
func overloadFromOtherFile() -> Bool { return false }
func useStructBeforeDeclaration() {
// Check structs from another file in the same module.
if FromOtherFile(v: "a") == FromOtherFile(v: "b") {}
let _: Int = FromOtherFile(v: "c").hashValue
FromOtherFile(v: "d").hash(into: &hasher)
if AlsoFromOtherFile(v: 3) == getFromOtherFile() {}
if YetAnotherFromOtherFile(v: 1.9) == overloadFromOtherFile() {}
}
// Even if the struct has only equatable/hashable members, it's not synthesized
// implicitly.
struct StructWithoutExplicitConformance {
let a: Int
let b: String
}
func structWithoutExplicitConformance() {
// This diagnostic is about `Equatable` because it's considered the best possible solution among other ones for operator `==`.
if StructWithoutExplicitConformance(a: 1, b: "b") == StructWithoutExplicitConformance(a: 2, b: "a") { } // expected-error{{referencing operator function '==' on 'Equatable' requires that 'StructWithoutExplicitConformance' conform to 'Equatable'}}
}
// Structs with non-hashable/equatable stored properties don't derive conformance.
struct NotHashable {}
struct StructWithNonHashablePayload: Hashable { // expected-error 2 {{does not conform}}
let a: NotHashable // expected-note {{stored property type 'NotHashable' does not conform to protocol 'Hashable', preventing synthesized conformance of 'StructWithNonHashablePayload' to 'Hashable'}}
// expected-note@-1 {{stored property type 'NotHashable' does not conform to protocol 'Equatable', preventing synthesized conformance of 'StructWithNonHashablePayload' to 'Equatable'}}
}
// ...but computed properties and static properties are not considered.
struct StructIgnoresComputedProperties: Hashable {
var a: Int
var b: String
static var staticComputed = NotHashable()
var computed: NotHashable { return NotHashable() }
}
func structIgnoresComputedProperties() {
if StructIgnoresComputedProperties(a: 1, b: "a") == StructIgnoresComputedProperties(a: 2, b: "c") {}
let _: Int = StructIgnoresComputedProperties(a: 3, b: "p").hashValue
StructIgnoresComputedProperties(a: 4, b: "q").hash(into: &hasher)
}
// Structs should be able to derive conformances based on the conformances of
// their generic arguments.
struct GenericHashable<T: Hashable>: Hashable {
let value: T
}
func genericHashable() {
if GenericHashable<String>(value: "a") == GenericHashable<String>(value: "b") { }
let _: Int = GenericHashable<String>(value: "c").hashValue
GenericHashable<String>(value: "c").hash(into: &hasher)
}
// But it should be an error if the generic argument doesn't have the necessary
// constraints to satisfy the conditions for derivation.
struct GenericNotHashable<T: Equatable>: Hashable { // expected-error 2 {{does not conform to protocol 'Hashable'}}
let value: T // expected-note 2 {{stored property type 'T' does not conform to protocol 'Hashable', preventing synthesized conformance of 'GenericNotHashable<T>' to 'Hashable'}}
}
func genericNotHashable() {
if GenericNotHashable<String>(value: "a") == GenericNotHashable<String>(value: "b") { }
let gnh = GenericNotHashable<String>(value: "b")
let _: Int = gnh.hashValue // No error. hashValue is always synthesized, even if Hashable derivation fails
gnh.hash(into: &hasher) // expected-error {{value of type 'GenericNotHashable<String>' has no member 'hash'}}
}
// Synthesis can be from an extension...
struct StructConformsInExtension {
let v: Int
}
extension StructConformsInExtension : Equatable {}
// and explicit conformance in an extension should also work.
public struct StructConformsAndImplementsInExtension {
let v: Int
}
extension StructConformsAndImplementsInExtension : Equatable {
public static func ==(lhs: StructConformsAndImplementsInExtension, rhs: StructConformsAndImplementsInExtension) -> Bool {
return true
}
}
// No explicit conformance and it cannot be derived.
struct NotExplicitlyHashableAndCannotDerive {
let v: NotHashable // expected-note {{stored property type 'NotHashable' does not conform to protocol 'Hashable', preventing synthesized conformance of 'NotExplicitlyHashableAndCannotDerive' to 'Hashable'}}
// expected-note@-1 {{stored property type 'NotHashable' does not conform to protocol 'Equatable', preventing synthesized conformance of 'NotExplicitlyHashableAndCannotDerive' to 'Equatable'}}
}
extension NotExplicitlyHashableAndCannotDerive : Hashable {} // expected-error 2 {{does not conform}}
// A struct with no stored properties trivially derives conformance.
struct NoStoredProperties: Hashable {}
// Verify that conformance (albeit manually implemented) can still be added to
// a type in a different file.
extension OtherFileNonconforming: Hashable {
static func ==(lhs: OtherFileNonconforming, rhs: OtherFileNonconforming) -> Bool {
return true
}
func hash(into hasher: inout Hasher) {}
}
// ...but synthesis in a type defined in another file doesn't work yet.
extension YetOtherFileNonconforming: Equatable {} // expected-error {{cannot be automatically synthesized in an extension in a different file to the type}}
// Verify that we can add Hashable conformance in an extension by only
// implementing hash(into:)
struct StructConformsAndImplementsHashIntoInExtension: Equatable {
let v: String
}
extension StructConformsAndImplementsHashIntoInExtension: Hashable {
func hash(into hasher: inout Hasher) {
hasher.combine(v)
}
}
func structConformsAndImplementsHashIntoInExtension() {
let _: Int = StructConformsAndImplementsHashIntoInExtension(v: "a").hashValue
StructConformsAndImplementsHashIntoInExtension(v: "b").hash(into: &hasher)
}
struct GenericHashIntoInExtension<T: Hashable>: Equatable {
let value: T
}
extension GenericHashIntoInExtension: Hashable {
func hash(into hasher: inout Hasher) {
hasher.combine(value)
}
}
func genericHashIntoInExtension() {
let _: Int = GenericHashIntoInExtension<String>(value: "a").hashValue
GenericHashIntoInExtension(value: "b").hash(into: &hasher)
}
// Conditional conformances should be able to be synthesized
struct GenericDeriveExtension<T> {
let value: T
}
extension GenericDeriveExtension: Equatable where T: Equatable {}
extension GenericDeriveExtension: Hashable where T: Hashable {}
// Incorrectly/insufficiently conditional shouldn't work
struct BadGenericDeriveExtension<T> {
let value: T // expected-note {{stored property type 'T' does not conform to protocol 'Hashable', preventing synthesized conformance of 'BadGenericDeriveExtension<T>' to 'Hashable'}}
// expected-note@-1 {{stored property type 'T' does not conform to protocol 'Equatable', preventing synthesized conformance of 'BadGenericDeriveExtension<T>' to 'Equatable'}}
}
extension BadGenericDeriveExtension: Equatable {}
// expected-error@-1 {{type 'BadGenericDeriveExtension<T>' does not conform to protocol 'Equatable'}}
extension BadGenericDeriveExtension: Hashable where T: Equatable {}
// expected-error@-1 {{type 'BadGenericDeriveExtension' does not conform to protocol 'Hashable'}}
// But some cases don't need to be conditional, even if they look similar to the
// above
struct AlwaysHashable<T>: Hashable {}
struct UnusedGenericDeriveExtension<T> {
let value: AlwaysHashable<T>
}
extension UnusedGenericDeriveExtension: Hashable {}
// Cross-file synthesis is still disallowed for conditional cases
extension GenericOtherFileNonconforming: Equatable where T: Equatable {}
// expected-error@-1{{implementation of 'Equatable' cannot be automatically synthesized in an extension in a different file to the type}}
// rdar://problem/41852654
// There is a conformance to Equatable (or at least, one that implies Equatable)
// in the same file as the type, so the synthesis is okay. Both orderings are
// tested, to catch choosing extensions based on the order of the files, etc.
protocol ImplierMain: Equatable {}
struct ImpliedMain: ImplierMain {}
extension ImpliedOther: ImplierMain {}
// Hashable conformances that rely on a manual implementation of `hashValue`
// should produce a deprecation warning.
struct OldSchoolStruct: Hashable {
static func ==(left: OldSchoolStruct, right: OldSchoolStruct) -> Bool {
return true
}
var hashValue: Int { return 42 }
// expected-warning@-1{{'Hashable.hashValue' is deprecated as a protocol requirement; conform type 'OldSchoolStruct' to 'Hashable' by implementing 'hash(into:)' instead}}
}
enum OldSchoolEnum: Hashable {
case foo
case bar
static func ==(left: OldSchoolEnum, right: OldSchoolEnum) -> Bool {
return true
}
var hashValue: Int { return 23 }
// expected-warning@-1{{'Hashable.hashValue' is deprecated as a protocol requirement; conform type 'OldSchoolEnum' to 'Hashable' by implementing 'hash(into:)' instead}}
}
class OldSchoolClass: Hashable {
static func ==(left: OldSchoolClass, right: OldSchoolClass) -> Bool {
return true
}
var hashValue: Int { return -9000 }
// expected-warning@-1{{'Hashable.hashValue' is deprecated as a protocol requirement; conform type 'OldSchoolClass' to 'Hashable' by implementing 'hash(into:)' instead}}
}
// However, it's okay to implement `hashValue` as long as `hash(into:)` is also
// provided.
struct MixedStruct: Hashable {
static func ==(left: MixedStruct, right: MixedStruct) -> Bool {
return true
}
func hash(into hasher: inout Hasher) {}
var hashValue: Int { return 42 }
}
enum MixedEnum: Hashable {
case foo
case bar
static func ==(left: MixedEnum, right: MixedEnum) -> Bool {
return true
}
func hash(into hasher: inout Hasher) {}
var hashValue: Int { return 23 }
}
class MixedClass: Hashable {
static func ==(left: MixedClass, right: MixedClass) -> Bool {
return true
}
func hash(into hasher: inout Hasher) {}
var hashValue: Int { return -9000 }
}
// Ensure equatable and hashable works with weak/unowned properties as well
struct Foo: Equatable, Hashable {
weak var foo: Bar?
unowned var bar: Bar
}
class Bar {
let bar: String
init(bar: String) {
self.bar = bar
}
}
extension Bar: Equatable, Hashable {
static func == (lhs: Bar, rhs: Bar) -> Bool {
return lhs.bar == rhs.bar
}
func hash(into hasher: inout Hasher) {}
}
// FIXME: Remove -verify-ignore-unknown.
// <unknown>:0: error: unexpected error produced: invalid redeclaration of 'hashValue'
// <unknown>:0: error: unexpected note produced: candidate has non-matching type '(Foo, Foo) -> Bool'
// <unknown>:0: error: unexpected note produced: candidate has non-matching type '<T> (Generic<T>, Generic<T>) -> Bool'
// <unknown>:0: error: unexpected note produced: candidate has non-matching type '(InvalidCustomHashable, InvalidCustomHashable) -> Bool'
// <unknown>:0: error: unexpected note produced: candidate has non-matching type '(EnumToUseBeforeDeclaration, EnumToUseBeforeDeclaration) -> Bool'
| apache-2.0 | f0de3d72dde0bc396c2e5831c290c2b3 | 37.689655 | 248 | 0.72653 | 4.023909 | false | false | false | false |
yanqingsmile/ChemicalCalculator | ChemicalCalculator/GroupDetailTableViewController.swift | 1 | 7083 | //
// GroupDetailTableViewController.swift
// ChemicalCalculator
//
// Created by Vivian Liu on 3/29/17.
// Copyright © 2017 Vivian Liu. All rights reserved.
//
import UIKit
import CoreData
import Mixpanel
class GroupDetailTableViewController: CoreDataTableViewController {
// MARK: - Properties
var group: Group?
// MARK: - View life cycle methods
override func viewDidLoad() {
super.viewDidLoad()
title = group?.title
// Set up tableview background view color
let bgView = UIView()
bgView.backgroundColor = UIColor.grayWhite()
tableView.backgroundView = bgView
// hide empty cells
tableView.tableFooterView = UIView()
// disable row selections
tableView.allowsSelection = false
// set up table view top distance to navigation bar
tableView.contentInset = UIEdgeInsets(top: 15, left: 0, bottom: 50, right: 0)
Mixpanel.mainInstance().track(event: "View group detail")
}
// MARK: - Table view data source
override func numberOfSections(in tableView: UITableView) -> Int {
return group == nil ? 0 : 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return group?.ingredients?.count ?? 0
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if let ingredients = group?.ingredients {
let ingredient = ingredients.object(at: indexPath.row) as! Solution
if ingredient.isDiluted {
let cell = tableView.dequeueReusableCell(withIdentifier: "dilutionCell", for: indexPath) as! SolutionTableViewCell
cell.nameLabel.text = ingredient.solute?.name
cell.concentrationLabel.text = String(describing: ingredient.finalConcentration) + " "
cell.concentrationUnitLabel.text = ingredient.concentrationUnit
cell.volumeLabel.text = String(describing: ingredient.finalVolume) + " "
cell.volumeUnitLabel.text = ingredient.volumeUnit
cell.stockNeededVolumeLabel.text = String(describing: ingredient.stockNeededVolume) + " "
cell.stockNeededVolumeUnitLabel.text = ingredient.stockNeededVolumeUnit
cell.stockConcentrationLabel.text = ingredient.stockConcentration?.components(separatedBy: " ")[0]
cell.stockConcentrationUnitLabel.text = ingredient.stockConcentration?.components(separatedBy: " ")[1]
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "MM/dd/yyyy"
let result = dateFormatter.string(from:ingredient.createdDate! as Date)
cell.createdDateLabel.text = result
cell.countLabel.text = String(describing: indexPath.row + 1)
return cell
} else {
let cell = tableView.dequeueReusableCell(withIdentifier: "solutionCell", for: indexPath) as! SolutionTableViewCell
cell.nameLabel.text = ingredient.solute?.name
cell.massLabel.text = String(describing: ingredient.soluteMass)
cell.massUnitLabel.text = ingredient.massUnit
cell.concentrationLabel.text = String(describing: ingredient.finalConcentration)
cell.concentrationUnitLabel.text = ingredient.concentrationUnit
cell.volumeLabel.text = String(describing: ingredient.finalVolume)
cell.volumeUnitLabel.text = ingredient.volumeUnit
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "MM/dd/yyyy"
let result = dateFormatter.string(from: ingredient.createdDate! as Date)
cell.createdDateLabel.text = result
cell.countLabel.text = String(describing: indexPath.row + 1)
return cell
}
}
return UITableViewCell()
}
/*
// Override to support conditional editing of the table view.
override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
// Return false if you do not want the specified item to be editable.
return true
}
*/
// Override to support editing the table view.
override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == .delete {
if let ingredientToDelete = self.group?.ingredients?[indexPath.row] as? Solution, let context = group?.managedObjectContext {
context.performAndWait({
let mutableIngredients = self.group!.ingredients!.mutableCopy() as! NSMutableOrderedSet
mutableIngredients.remove(ingredientToDelete)
self.group!.ingredients = mutableIngredients.copy() as? NSOrderedSet
try? context.save()
})
tableView.reloadData()
}
} 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 func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
if let solution = group?.ingredients?[indexPath.row] as? Solution {
if solution.isDiluted {
return 200
}
return 180
}
return 200
}
// MARK: - Navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "addNewIngredientToGroup" {
if let navcon = segue.destination as? UINavigationController, let solutionListTVC = navcon.visibleViewController as? SavedSolutionTableViewController {
solutionListTVC.isEditing = true
}
}
}
@IBAction func unwindToGroupDetailTableViewController(sender: UIStoryboardSegue) {
Mixpanel.mainInstance().track(event: "Add button in GroupDetail VC clicked")
if let sourceTVC = sender.source as? SavedSolutionTableViewController, let selectedIndexPaths = sourceTVC.tableView.indexPathsForSelectedRows {
let selectedSolutions = selectedIndexPaths.map{sourceTVC.fetchedResultsController?.object(at: $0) as! Solution}
group!.managedObjectContext?.performAndWait({
let mutableIngredients = self.group!.ingredients!.mutableCopy() as! NSMutableOrderedSet
mutableIngredients.addObjects(from: selectedSolutions)
self.group!.ingredients = mutableIngredients.copy() as? NSOrderedSet
try? self.group!.managedObjectContext?.save()
})
}
tableView.reloadData()
}
}
| mit | 5bf3c440cae312fe4d686e6521bcf225 | 41.662651 | 163 | 0.630613 | 5.511284 | false | false | false | false |
EmberTown/ember-hearth | Ember Hearth/StatusBarManager.swift | 1 | 4637 | //
// StatusBarManager.swift
// Ember Hearth
//
// Created by Thomas Sunde Nielsen on 26.04.15.
// Copyright (c) 2015 Thomas Sunde Nielsen. All rights reserved.
//
import Cocoa
import MASShortcut
let _sharedManager = StatusBarManager()
class StatusBarManager: NSObject {
class var sharedManager: StatusBarManager {
get {return _sharedManager}
}
var statusBarItem: NSStatusItem?
var statusBarMenu: NSMenu?
var nameMenuItem: NSMenuItem?
var runServerMenuItem: NSMenuItem?
var terminateMenuItem: NSMenuItem?
let noProjectString = "No project selected"
var appDelegate: AppDelegate {
get {
return NSApplication.sharedApplication().delegate as! AppDelegate
}
}
override init() {
super.init()
NSNotificationCenter.defaultCenter().addObserver(self, selector: "serverStarted:", name: "serverStarted", object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: "serverStopped:", name: "serverStopped", object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: "serverStoppedWithError:", name: "serverStoppedWithError", object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: "serverStarting:", name: "serverStarting", object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: "activeProjectSet:", name: "activeProjectSet", object: nil)
}
func showStatusBarItem() {
let statusIcon = NSImage(named: "StatusBarIconIdle")
statusIcon?.setTemplate(true)
statusBarItem = NSStatusBar.systemStatusBar().statusItemWithLength( -2 ) // NSSquareStatusItemLength
statusBarItem?.button?.setAccessibilityTitle("Ember Hearth")
statusBarItem?.button?.image = statusIcon
statusBarMenu = NSMenu(title: "Ember Hearth")
let title = appDelegate.activeProject?.name ?? noProjectString
nameMenuItem = NSMenuItem(title: "\(title)", action: nil, keyEquivalent: "")
nameMenuItem?.enabled = false
statusBarMenu?.addItem(nameMenuItem!)
runServerMenuItem = NSMenuItem(title: "Run Server", action: "toggleServer:", keyEquivalent: "")
statusBarMenu?.addItem(runServerMenuItem!)
let separator = NSMenuItem.separatorItem()
statusBarMenu?.addItem(separator)
terminateMenuItem = NSMenuItem(title: "Quit Ember Hearth", action: "terminate:", keyEquivalent: "")
statusBarMenu?.addItem(terminateMenuItem!)
statusBarMenu?.autoenablesItems = false
runServerMenuItem?.enabled = true
statusBarItem?.menu = statusBarMenu
MASShortcutBinder.sharedBinder().bindShortcutWithDefaultsKey(appDelegate.runServerHotKey, toAction: { () -> Void in
self.appDelegate.toggleServer(nil)
})
}
func hideStatusBarItem() {
if statusBarItem != nil {
NSStatusBar.systemStatusBar().removeStatusItem(statusBarItem!)
}
}
// MARK: Notification handling
func serverStarting(notification: NSNotification?) {
updateStatusBarButton("StatusBarIconStarting", accessibilityTitle: "Ember Hearth - Starting Server")
runServerMenuItem?.enabled = true
runServerMenuItem?.title = "Stop booting server"
}
func serverStarted(notification: NSNotification?) {
updateStatusBarButton("StatusBarIconRunning", accessibilityTitle: "Ember Hearth - Running Server")
runServerMenuItem?.enabled = true
runServerMenuItem?.title = "Stop server"
}
func serverStopped(notification: NSNotification?) {
updateStatusBarButton("StatusBarIconIdle", accessibilityTitle: "Ember Hearth")
runServerMenuItem?.enabled = true
runServerMenuItem?.title = "Run server"
}
func serverStoppedWithError(notification: NSNotification?) {
updateStatusBarButton("StatusBarIconError", accessibilityTitle: "Ember Hearth - Server Failed Miserably")
runServerMenuItem?.enabled = true
runServerMenuItem?.title = "Run server"
}
func activeProjectSet(notification: NSNotification?) {
nameMenuItem?.title = (notification?.object as? Project)?.name ?? noProjectString
}
// MARK: UI Updates
func updateStatusBarButton(imageName: String, accessibilityTitle: String) {
let image = NSImage(named: imageName)
image?.setTemplate(true)
statusBarItem?.button?.image = image
statusBarItem?.button?.setAccessibilityTitle(accessibilityTitle)
}
}
| mit | 0f1baeda70df561dce0712d29f21a065 | 38.974138 | 144 | 0.687513 | 5.129425 | false | false | false | false |
alsoyay/AYSwift | Pod/Classes/UILayerView.swift | 1 | 2367 | //
// Created by Daniela Postigo on 9/8/15.
//
import Foundation
import Brief
@IBDesignable
@objc(UILayerView) public class UILayerView: UIView {
@IBInspectable public var shape: String = "hamburger" {
didSet {
// let shape = Shape(rawValue: newValue)!
self.shapeLayer = CAShapeLayer.shape(Shape(rawValue: shape)!)
self.layer.mask = self.shapeLayer
// self.frame = self.shapeLayer!.bounds
// self.setNeedsLayout()
// self.customLayerShape = newValue
}
}
public var customLayer: CALayer?
public var shapeLayer: CAShapeLayer?
// required public init(coder aDecoder: NSCoder) {
// super.init(coder: aDecoder)
// setTranslatesAutoresizingMaskIntoConstraints(false)
// }
// public required init(coder aDecoder: NSCoder) {
// super.init(coder: aDecoder)
// self.setTranslatesAutoresizingMaskIntoConstraints(false)
// }
public override func systemLayoutSizeFittingSize(targetSize: CGSize) -> CGSize {
return CGSize(width: 40, height: 100)
}
public override func intrinsicContentSize() -> CGSize {
// let height = self.shapeLayer?.height
return CGSize(width: 20, height: 20)
// return CGSize(width: 20, height: self.shapeLayer != nil ? self.shapeLayer.bounds.size.height : UIViewNoIntrinsicMetric)
}
public override class func requiresConstraintBasedLayout() -> Bool {
return true
}
public override func layoutSubviews() {
let path = UIBezierPath.hamburger(CGSize(width: self.frame.size.width, height: 1))
self.shapeLayer?.path = path.CGPath
self.shapeLayer?.height = path.bounds.size.height
// self.shapeLayer?.frame.origin.y = path.bounds.size.height
// self.shapeLayer?.anchorPoint.y = self.center.y
self.shapeLayer?.frame.origin.y = round((self.height - self.shapeLayer!.height) * 0.5)
// self.shapeLayer?.anchorPoint.y = self.shapeLayer!.height/2
// self.shapeLayer?.frame.origin.y = round(self.height - self.shapeLayer!.height / 2)
//
// self.shapeLayer?.anchorPoint.y = self.shapeLayer!.path.bounds.size.height
// self.shapeLayer?.anchorPoint.y = CGPathGetPathBoundingBox(self.shapeLayer!.path).height
// if self.shapeLayer != nil {
// }
}
} | mit | c2e47e4b51d9f199c1c69ae5789f7511 | 30.157895 | 129 | 0.65357 | 4.204263 | false | false | false | false |
SteveBarnegren/SBSwiftUtils | SBSwiftUtils/Extensions/Array/Array+Filtering.swift | 1 | 955 | //
// Array+Filtering.swift
// SBSwiftUtils
//
// Created by Steve Barnegren on 13/02/2018.
// Copyright © 2018 SteveBarnegren. All rights reserved.
//
import Foundation
public extension Array {
/// Mutating version of the Swift standard library `filter()` function.
///
/// var array = [1, 2, 3, 4, 5]
/// array.filterInPlace { $0 % == 0 }
/// print("\(array)") // [2, 4]
///
/// - Parameter isIncluded: Closure to determine if an element should be included in
/// the array
mutating func filterInPlace(isIncluded: (Element) -> Bool) {
self = self.filter(isIncluded)
}
/// Removes elements from the array where `shouldRemove` returns `true`
///
/// - Parameter shouldRemove: Closure returning `true` if an element should be
/// removed
mutating func remove(shouldRemove: (Element) -> Bool) {
self = self.filter { shouldRemove($0) == false }
}
}
| mit | d4ce8d4d319b1b5c16892bfce51ca3a9 | 28.8125 | 88 | 0.610063 | 4.076923 | false | false | false | false |
SteveBarnegren/SBSwiftUtils | SBSwiftUtils/Extensions/Collection/Collection+Extensions.swift | 1 | 1359 | //
// Collection+Extensions.swift
// SBSwiftUtils
//
// Created by Steve Barnegren on 13/02/2018.
// Copyright © 2018 SteveBarnegren. All rights reserved.
//
import Foundation
// MARK: - Last Index
public extension Collection {
/// The last index of the collection, or `nil` if the collection is empty
var lastIndex: Int? {
if count - 1 >= 0 {
return Int(count) - 1
} else {
return nil
}
}
}
// MARK: - Is Ascending / Descending
public extension Collection where Element: Comparable {
/// `true` if the elements in the collection are in ascending order
var isAscending: Bool {
var previousItem: Element?
for item in self {
if let previous = previousItem, previous > item {
return false
}
previousItem = item
}
return true
}
/// `true` if the elements in the collection are in descending order
var isDescending: Bool {
var previousItem: Element?
for item in self {
if let previous = previousItem, previous < item {
return false
}
previousItem = item
}
return true
}
}
| mit | f97bfaa82b0b75050dacfdca98ecaa4e | 20.555556 | 77 | 0.518409 | 5.124528 | false | false | false | false |
dinhchitrung/SlideMenuControllerSwift | Source/SlideMenuController.swift | 1 | 34992 | //
// SlideMenuController.swift
//
// Created by Yuji Hato on 12/3/14.
//
import Foundation
import UIKit
class SlideMenuOption {
var leftViewWidth: CGFloat = 270.0
var leftBezelWidth: CGFloat = 16.0
var contentViewScale: CGFloat = 0.96
var contentViewOpacity: CGFloat = 0.5
var shadowOpacity: CGFloat = 0.0
var shadowRadius: CGFloat = 0.0
var shadowOffset: CGSize = CGSizeMake(0,0)
var panFromBezel: Bool = true
var animationDuration: CGFloat = 0.4
var rightViewWidth: CGFloat = 270.0
var rightBezelWidth: CGFloat = 16.0
var rightPanFromBezel: Bool = true
var hideStatusBar: Bool = true
var pointOfNoReturnWidth: CGFloat = 44.0
init() {
}
}
class SlideMenuController: UIViewController, UIGestureRecognizerDelegate {
enum SlideAction {
case Open
case Close
}
enum TrackAction {
case TapOpen
case TapClose
case FlickOpen
case FlickClose
}
struct PanInfo {
var action: SlideAction
var shouldBounce: Bool
var velocity: CGFloat
}
var opacityView = UIView()
var mainContainerView = UIView()
var leftContainerView = UIView()
var rightContainerView = UIView()
var mainViewController: UIViewController?
var leftViewController: UIViewController?
var leftPanGesture: UIPanGestureRecognizer?
var leftTapGetsture: UITapGestureRecognizer?
var rightViewController: UIViewController?
var rightPanGesture: UIPanGestureRecognizer?
var rightTapGesture: UITapGestureRecognizer?
var options = SlideMenuOption()
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) {
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
}
convenience init(mainViewController: UIViewController, leftMenuViewController: UIViewController) {
self.init()
self.mainViewController = mainViewController
self.leftViewController = leftMenuViewController
self.initView()
}
convenience init(mainViewController: UIViewController, rightMenuViewController: UIViewController) {
self.init()
self.mainViewController = mainViewController
self.rightViewController = rightMenuViewController
self.initView()
}
convenience init(mainViewController: UIViewController, leftMenuViewController: UIViewController, rightMenuViewController: UIViewController) {
self.init()
self.mainViewController = mainViewController
self.leftViewController = leftMenuViewController
self.rightViewController = rightMenuViewController
self.initView()
}
deinit { }
func initView() {
mainContainerView = UIView(frame: self.view.bounds)
mainContainerView.backgroundColor = UIColor.clearColor()
mainContainerView.autoresizingMask = UIViewAutoresizing.FlexibleHeight | UIViewAutoresizing.FlexibleWidth
self.view.insertSubview(mainContainerView, atIndex: 0)
var opacityframe: CGRect = self.view.bounds
var opacityOffset: CGFloat = 0
opacityframe.origin.y = opacityframe.origin.y + opacityOffset
opacityframe.size.height = opacityframe.size.height - opacityOffset
opacityView = UIView(frame: opacityframe)
opacityView.backgroundColor = UIColor.blackColor()
opacityView.autoresizingMask = UIViewAutoresizing.FlexibleHeight | UIViewAutoresizing.FlexibleWidth
opacityView.layer.opacity = 0.0
self.view.insertSubview(opacityView, atIndex: 1)
var leftFrame: CGRect = self.view.bounds
leftFrame.size.width = self.options.leftViewWidth
leftFrame.origin.x = self.leftMinOrigin();
var leftOffset: CGFloat = 0
leftFrame.origin.y = leftFrame.origin.y + leftOffset
leftFrame.size.height = leftFrame.size.height - leftOffset
leftContainerView = UIView(frame: leftFrame)
leftContainerView.backgroundColor = UIColor.clearColor()
leftContainerView.autoresizingMask = UIViewAutoresizing.FlexibleHeight
self.view.insertSubview(leftContainerView, atIndex: 2)
var rightFrame: CGRect = self.view.bounds
rightFrame.size.width = self.options.rightViewWidth
rightFrame.origin.x = self.rightMinOrigin()
var rightOffset: CGFloat = 0
rightFrame.origin.y = rightFrame.origin.y + rightOffset;
rightFrame.size.height = rightFrame.size.height - rightOffset
rightContainerView = UIView(frame: rightFrame)
rightContainerView.backgroundColor = UIColor.clearColor()
rightContainerView.autoresizingMask = UIViewAutoresizing.FlexibleHeight
self.view.insertSubview(rightContainerView, atIndex: 3)
self.addLeftGestures()
self.addRightGestures()
}
override func willRotateToInterfaceOrientation(toInterfaceOrientation: UIInterfaceOrientation, duration: NSTimeInterval) {
super.willRotateToInterfaceOrientation(toInterfaceOrientation, duration: duration)
self.mainContainerView.transform = CGAffineTransformMakeScale(1.0, 1.0)
self.leftContainerView.hidden = true
self.rightContainerView.hidden = true
}
override func didRotateFromInterfaceOrientation(fromInterfaceOrientation: UIInterfaceOrientation) {
super.didRotateFromInterfaceOrientation(fromInterfaceOrientation)
self.closeLeftNonAnimation()
self.closeRightNonAnimation()
self.leftContainerView.hidden = false
self.rightContainerView.hidden = false
self.removeLeftGestures()
self.removeRightGestures()
self.addLeftGestures()
self.addRightGestures()
}
override func viewDidLoad() {
super.viewDidLoad()
self.edgesForExtendedLayout = UIRectEdge.None
}
override func viewWillLayoutSubviews() {
// topLayoutGuideの値が確定するこのタイミングで各種ViewControllerをセットする
self.setUpViewController(self.mainContainerView, targetViewController: self.mainViewController)
self.setUpViewController(self.leftContainerView, targetViewController: self.leftViewController)
self.setUpViewController(self.rightContainerView, targetViewController: self.rightViewController)
}
override func openLeft() {
self.setOpenWindowLevel()
//leftViewControllerのviewWillAppearを呼ぶため
self.leftViewController?.beginAppearanceTransition(self.isLeftHidden(), animated: true)
self.openLeftWithVelocity(0.0)
self.track(.TapOpen)
}
override func openRight() {
self.setOpenWindowLevel()
//menuViewControllerのviewWillAppearを呼ぶため
self.rightViewController?.beginAppearanceTransition(self.isRightHidden(), animated: true)
self.openRightWithVelocity(0.0)
}
override func closeLeft() {
self.leftViewController?.beginAppearanceTransition(self.isLeftHidden(), animated: true)
self.closeLeftWithVelocity(0.0)
self.setCloseWindowLebel()
}
override func closeRight() {
self.rightViewController?.beginAppearanceTransition(self.isRightHidden(), animated: true)
self.closeRightWithVelocity(0.0)
self.setCloseWindowLebel()
}
func addLeftGestures() {
if (self.leftViewController != nil) {
if self.leftPanGesture == nil {
self.leftPanGesture = UIPanGestureRecognizer(target: self, action: "handleLeftPanGesture:")
self.leftPanGesture!.delegate = self
self.view.addGestureRecognizer(self.leftPanGesture!)
}
if self.leftTapGetsture == nil {
self.leftTapGetsture = UITapGestureRecognizer(target: self, action: "toggleLeft")
self.leftTapGetsture!.delegate = self
self.view.addGestureRecognizer(self.leftTapGetsture!)
}
}
}
func addRightGestures() {
if (self.rightViewController != nil) {
if self.rightPanGesture == nil {
self.rightPanGesture = UIPanGestureRecognizer(target: self, action: "handleRightPanGesture:")
self.rightPanGesture!.delegate = self
self.view.addGestureRecognizer(self.rightPanGesture!)
}
if self.rightTapGesture == nil {
self.rightTapGesture = UITapGestureRecognizer(target: self, action: "toggleRight")
self.rightTapGesture!.delegate = self
self.view.addGestureRecognizer(self.rightTapGesture!)
}
}
}
func removeLeftGestures() {
if self.leftPanGesture != nil {
self.view.removeGestureRecognizer(self.leftPanGesture!)
self.leftPanGesture = nil
}
if self.leftTapGetsture != nil {
self.view.removeGestureRecognizer(self.leftTapGetsture!)
self.leftTapGetsture = nil
}
}
func removeRightGestures() {
if self.rightPanGesture != nil {
self.view.removeGestureRecognizer(self.rightPanGesture!)
self.rightPanGesture = nil
}
if self.rightTapGesture != nil {
self.view.removeGestureRecognizer(self.rightTapGesture!)
self.rightTapGesture = nil
}
}
func isTagetViewController() -> Bool {
// Function to determine the target ViewController
// Please to override it if necessary
return true
}
func track(trackAction: TrackAction) {
// function is for tracking
// Please to override it if necessary
}
struct LeftPanState {
static var frameAtStartOfPan: CGRect = CGRectZero
static var startPointOfPan: CGPoint = CGPointZero
static var wasOpenAtStartOfPan: Bool = false
static var wasHiddenAtStartOfPan: Bool = false
}
func handleLeftPanGesture(panGesture: UIPanGestureRecognizer) {
if !self.isTagetViewController() {
return
}
if self.isRightOpen() {
return
}
switch panGesture.state {
case UIGestureRecognizerState.Began:
LeftPanState.frameAtStartOfPan = self.leftContainerView.frame
LeftPanState.startPointOfPan = panGesture.locationInView(self.view)
LeftPanState.wasOpenAtStartOfPan = self.isLeftOpen()
LeftPanState.wasHiddenAtStartOfPan = self.isLeftHidden()
self.leftViewController?.beginAppearanceTransition(LeftPanState.wasHiddenAtStartOfPan, animated: true)
self.addShadowToView(self.leftContainerView)
self.setOpenWindowLevel()
case UIGestureRecognizerState.Changed:
var translation: CGPoint = panGesture.translationInView(panGesture.view!)
self.leftContainerView.frame = self.applyLeftTranslation(translation, toFrame: LeftPanState.frameAtStartOfPan)
self.applyLeftOpacity()
self.applyLeftContentViewScale()
case UIGestureRecognizerState.Ended:
var velocity:CGPoint = panGesture.velocityInView(panGesture.view)
var panInfo: PanInfo = self.panLeftResultInfoForVelocity(velocity)
if panInfo.action == .Open {
if !LeftPanState.wasHiddenAtStartOfPan {
self.leftViewController?.beginAppearanceTransition(true, animated: true)
}
self.openLeftWithVelocity(panInfo.velocity)
self.track(.FlickOpen)
} else {
if LeftPanState.wasHiddenAtStartOfPan {
self.leftViewController?.beginAppearanceTransition(false, animated: true)
}
self.closeLeftWithVelocity(panInfo.velocity)
self.setCloseWindowLebel()
self.track(.FlickClose)
}
default:
break
}
}
struct RightPanState {
static var frameAtStartOfPan: CGRect = CGRectZero
static var startPointOfPan: CGPoint = CGPointZero
static var wasOpenAtStartOfPan: Bool = false
static var wasHiddenAtStartOfPan: Bool = false
}
func handleRightPanGesture(panGesture: UIPanGestureRecognizer) {
if !self.isTagetViewController() {
return
}
if self.isLeftOpen() {
return
}
switch panGesture.state {
case UIGestureRecognizerState.Began:
RightPanState.frameAtStartOfPan = self.rightContainerView.frame
RightPanState.startPointOfPan = panGesture.locationInView(self.view)
RightPanState.wasOpenAtStartOfPan = self.isRightOpen()
RightPanState.wasHiddenAtStartOfPan = self.isRightHidden()
self.rightViewController?.beginAppearanceTransition(RightPanState.wasHiddenAtStartOfPan, animated: true)
self.addShadowToView(self.rightContainerView)
self.setOpenWindowLevel()
case UIGestureRecognizerState.Changed:
var translation: CGPoint = panGesture.translationInView(panGesture.view!)
self.rightContainerView.frame = self.applyRightTranslation(translation, toFrame: RightPanState.frameAtStartOfPan)
self.applyRightOpacity()
self.applyRightContentViewScale()
case UIGestureRecognizerState.Ended:
var velocity: CGPoint = panGesture.velocityInView(panGesture.view)
var panInfo: PanInfo = self.panRightResultInfoForVelocity(velocity)
if panInfo.action == .Open {
if !RightPanState.wasHiddenAtStartOfPan {
self.rightViewController?.beginAppearanceTransition(true, animated: true)
}
self.openRightWithVelocity(panInfo.velocity)
} else {
if RightPanState.wasHiddenAtStartOfPan {
self.rightViewController?.beginAppearanceTransition(false, animated: true)
}
self.closeRightWithVelocity(panInfo.velocity)
self.setCloseWindowLebel()
}
default:
break
}
}
func openLeftWithVelocity(velocity: CGFloat) {
var xOrigin: CGFloat = self.leftContainerView.frame.origin.x
var finalXOrigin: CGFloat = 0.0
var frame = self.leftContainerView.frame;
frame.origin.x = finalXOrigin;
var duration: NSTimeInterval = Double(self.options.animationDuration)
if velocity != 0.0 {
duration = Double(fabs(xOrigin - finalXOrigin) / velocity)
duration = Double(fmax(0.1, fmin(1.0, duration)))
}
self.addShadowToView(self.leftContainerView)
UIView.animateWithDuration(duration, delay: 0.0, options: UIViewAnimationOptions.CurveEaseInOut, animations: { () -> Void in
self.leftContainerView.frame = frame
self.opacityView.layer.opacity = Float(self.options.contentViewOpacity)
self.mainContainerView.transform = CGAffineTransformMakeScale(self.options.contentViewScale, self.options.contentViewScale)
}) { (Bool) -> Void in
self.disableContentInteraction()
self.leftViewController?.endAppearanceTransition()
}
}
func openRightWithVelocity(velocity: CGFloat) {
var xOrigin: CGFloat = self.rightContainerView.frame.origin.x
// CGFloat finalXOrigin = self.options.rightViewOverlapWidth;
var finalXOrigin: CGFloat = CGRectGetWidth(self.view.bounds) - self.rightContainerView.frame.size.width
var frame = self.rightContainerView.frame
frame.origin.x = finalXOrigin
var duration: NSTimeInterval = Double(self.options.animationDuration)
if velocity != 0.0 {
duration = Double(fabs(xOrigin - CGRectGetWidth(self.view.bounds)) / velocity)
duration = Double(fmax(0.1, fmin(1.0, duration)))
}
self.addShadowToView(self.rightContainerView)
UIView.animateWithDuration(duration, delay: 0.0, options: UIViewAnimationOptions.CurveEaseInOut, animations: { () -> Void in
self.rightContainerView.frame = frame
self.opacityView.layer.opacity = Float(self.options.contentViewOpacity)
self.mainContainerView.transform = CGAffineTransformMakeScale(self.options.contentViewScale, self.options.contentViewScale)
}) { (Bool) -> Void in
self.disableContentInteraction()
self.rightViewController?.endAppearanceTransition()
}
}
func closeLeftWithVelocity(velocity: CGFloat) {
var xOrigin: CGFloat = self.leftContainerView.frame.origin.x
var finalXOrigin: CGFloat = self.leftMinOrigin()
var frame: CGRect = self.leftContainerView.frame;
frame.origin.x = finalXOrigin
var duration: NSTimeInterval = Double(self.options.animationDuration)
if velocity != 0.0 {
duration = Double(fabs(xOrigin - finalXOrigin) / velocity)
duration = Double(fmax(0.1, fmin(1.0, duration)))
}
UIView.animateWithDuration(duration, delay: 0.0, options: UIViewAnimationOptions.CurveEaseInOut, animations: { () -> Void in
self.leftContainerView.frame = frame
self.opacityView.layer.opacity = 0.0
self.mainContainerView.transform = CGAffineTransformMakeScale(1.0, 1.0)
}) { (Bool) -> Void in
self.removeShadow(self.leftContainerView)
self.enableContentInteraction()
self.leftViewController?.endAppearanceTransition()
}
}
func closeRightWithVelocity(velocity: CGFloat) {
var xOrigin: CGFloat = self.rightContainerView.frame.origin.x
var finalXOrigin: CGFloat = CGRectGetWidth(self.view.bounds)
var frame: CGRect = self.rightContainerView.frame
frame.origin.x = finalXOrigin
var duration: NSTimeInterval = Double(self.options.animationDuration)
if velocity != 0.0 {
duration = Double(fabs(xOrigin - CGRectGetWidth(self.view.bounds)) / velocity)
duration = Double(fmax(0.1, fmin(1.0, duration)))
}
UIView.animateWithDuration(duration, delay: 0.0, options: UIViewAnimationOptions.CurveEaseInOut, animations: { () -> Void in
self.rightContainerView.frame = frame
self.opacityView.layer.opacity = 0.0
self.mainContainerView.transform = CGAffineTransformMakeScale(1.0, 1.0)
}) { (Bool) -> Void in
self.removeShadow(self.rightContainerView)
self.enableContentInteraction()
self.rightViewController?.endAppearanceTransition()
}
}
override func toggleLeft() {
if self.isLeftOpen() {
self.closeLeft()
self.setCloseWindowLebel()
// closeMenuはメニュータップ時にも呼ばれるため、closeタップのトラッキングはここに入れる
self.track(.TapClose)
} else {
self.openLeft()
}
}
func isLeftOpen() -> Bool {
return self.leftContainerView.frame.origin.x == 0.0
}
func isLeftHidden() -> Bool {
return self.leftContainerView.frame.origin.x <= self.leftMinOrigin()
}
override func toggleRight() {
if self.isRightOpen() {
self.closeRight()
self.setCloseWindowLebel()
} else {
self.openRight()
}
}
func isRightOpen() -> Bool {
return self.rightContainerView.frame.origin.x == CGRectGetWidth(self.view.bounds) - self.rightContainerView.frame.size.width
}
func isRightHidden() -> Bool {
return self.rightContainerView.frame.origin.x >= CGRectGetWidth(self.view.bounds)
}
func changeMainViewController(mainViewController: UIViewController, close: Bool) {
self.removeViewController(self.mainViewController)
self.mainViewController = mainViewController
self.setUpViewController(self.mainContainerView, targetViewController: self.mainViewController)
if (close) {
self.closeLeft()
self.closeRight()
}
}
func changeLeftViewController(leftViewController: UIViewController, closeLeft:Bool) {
self.removeViewController(self.leftViewController)
self.leftViewController = leftViewController
self.setUpViewController(self.leftContainerView, targetViewController: self.leftViewController)
if (closeLeft) {
self.closeLeft()
}
}
func changeRightViewController(rightViewController: UIViewController, closeRight:Bool) {
self.removeViewController(self.rightViewController)
self.rightViewController = rightViewController;
self.setUpViewController(self.rightContainerView, targetViewController: self.rightViewController)
if (closeRight) {
self.closeRight()
}
}
private func leftMinOrigin() -> CGFloat {
return -self.options.leftViewWidth
}
private func rightMinOrigin() -> CGFloat {
return CGRectGetWidth(self.view.bounds)
}
private func panLeftResultInfoForVelocity(velocity: CGPoint) -> PanInfo {
var thresholdVelocity: CGFloat = 1000.0
var pointOfNoReturn: CGFloat = CGFloat(floor(self.leftMinOrigin())) + self.options.pointOfNoReturnWidth
var leftOrigin: CGFloat = self.leftContainerView.frame.origin.x
var panInfo: PanInfo = PanInfo(action: .Close, shouldBounce: false, velocity: 0.0)
panInfo.action = leftOrigin <= pointOfNoReturn ? .Close : .Open;
if velocity.x >= thresholdVelocity {
panInfo.action = .Open
panInfo.velocity = velocity.x
} else if velocity.x <= (-1.0 * thresholdVelocity) {
panInfo.action = .Close
panInfo.velocity = velocity.x
}
return panInfo
}
private func panRightResultInfoForVelocity(velocity: CGPoint) -> PanInfo {
var thresholdVelocity: CGFloat = -1000.0
var pointOfNoReturn: CGFloat = CGFloat(floor(CGRectGetWidth(self.view.bounds)) - self.options.pointOfNoReturnWidth)
var rightOrigin: CGFloat = self.rightContainerView.frame.origin.x
var panInfo: PanInfo = PanInfo(action: .Close, shouldBounce: false, velocity: 0.0)
panInfo.action = rightOrigin >= pointOfNoReturn ? .Close : .Open
if velocity.x <= thresholdVelocity {
panInfo.action = .Open
panInfo.velocity = velocity.x
} else if (velocity.x >= (-1.0 * thresholdVelocity)) {
panInfo.action = .Close
panInfo.velocity = velocity.x
}
return panInfo
}
private func applyLeftTranslation(translation: CGPoint, toFrame:CGRect) -> CGRect {
var newOrigin: CGFloat = toFrame.origin.x
newOrigin += translation.x
var minOrigin: CGFloat = self.leftMinOrigin()
var maxOrigin: CGFloat = 0.0
var newFrame: CGRect = toFrame
if newOrigin < minOrigin {
newOrigin = minOrigin
} else if newOrigin > maxOrigin {
newOrigin = maxOrigin
}
newFrame.origin.x = newOrigin
return newFrame
}
private func applyRightTranslation(translation: CGPoint, toFrame: CGRect) -> CGRect {
var newOrigin: CGFloat = toFrame.origin.x
newOrigin += translation.x
var minOrigin: CGFloat = self.rightMinOrigin()
// var maxOrigin: CGFloat = self.options.rightViewOverlapWidth
var maxOrigin: CGFloat = self.rightMinOrigin() - self.rightContainerView.frame.size.width
var newFrame: CGRect = toFrame
if newOrigin > minOrigin {
newOrigin = minOrigin
} else if newOrigin < maxOrigin {
newOrigin = maxOrigin
}
newFrame.origin.x = newOrigin
return newFrame
}
private func getOpenedLeftRatio() -> CGFloat {
var width: CGFloat = self.leftContainerView.frame.size.width
var currentPosition: CGFloat = self.leftContainerView.frame.origin.x - self.leftMinOrigin()
return currentPosition / width
}
private func getOpenedRightRatio() -> CGFloat {
var width: CGFloat = self.rightContainerView.frame.size.width
var currentPosition: CGFloat = self.rightContainerView.frame.origin.x
return -(currentPosition - CGRectGetWidth(self.view.bounds)) / width
}
private func applyLeftOpacity() {
var openedLeftRatio: CGFloat = self.getOpenedLeftRatio()
var opacity: CGFloat = self.options.contentViewOpacity * openedLeftRatio
self.opacityView.layer.opacity = Float(opacity)
}
private func applyRightOpacity() {
var openedRightRatio: CGFloat = self.getOpenedRightRatio()
var opacity: CGFloat = self.options.contentViewOpacity * openedRightRatio
self.opacityView.layer.opacity = Float(opacity)
}
private func applyLeftContentViewScale() {
var openedLeftRatio: CGFloat = self.getOpenedLeftRatio()
var scale: CGFloat = 1.0 - ((1.0 - self.options.contentViewScale) * openedLeftRatio);
self.mainContainerView.transform = CGAffineTransformMakeScale(scale, scale)
}
private func applyRightContentViewScale() {
var openedRightRatio: CGFloat = self.getOpenedRightRatio()
var scale: CGFloat = 1.0 - ((1.0 - self.options.contentViewScale) * openedRightRatio)
self.mainContainerView.transform = CGAffineTransformMakeScale(scale, scale)
}
private func addShadowToView(targetContainerView: UIView) {
targetContainerView.layer.masksToBounds = false
targetContainerView.layer.shadowOffset = self.options.shadowOffset
targetContainerView.layer.shadowOpacity = Float(self.options.shadowOpacity)
targetContainerView.layer.shadowRadius = self.options.shadowRadius
targetContainerView.layer.shadowPath = UIBezierPath(rect: targetContainerView.bounds).CGPath
}
private func removeShadow(targetContainerView: UIView) {
targetContainerView.layer.masksToBounds = true
self.mainContainerView.layer.opacity = 1.0
}
private func removeContentOpacity() {
self.opacityView.layer.opacity = 0.0
}
private func addContentOpacity() {
self.opacityView.layer.opacity = Float(self.options.contentViewOpacity)
}
private func disableContentInteraction() {
self.mainContainerView.userInteractionEnabled = false
}
private func enableContentInteraction() {
self.mainContainerView.userInteractionEnabled = true
}
private func setOpenWindowLevel() {
if (self.options.hideStatusBar) {
dispatch_async(dispatch_get_main_queue(), {
if let window = UIApplication.sharedApplication().keyWindow {
window.windowLevel = UIWindowLevelStatusBar + 1
}
})
}
}
private func setCloseWindowLebel() {
if (self.options.hideStatusBar) {
dispatch_async(dispatch_get_main_queue(), {
if let window = UIApplication.sharedApplication().keyWindow {
window.windowLevel = UIWindowLevelNormal
}
})
}
}
private func setUpViewController(targetView: UIView, targetViewController: UIViewController?) {
if let viewController = targetViewController {
self.addChildViewController(viewController)
viewController.view.frame = targetView.bounds
targetView.addSubview(viewController.view)
viewController.didMoveToParentViewController(self)
}
}
private func removeViewController(viewController: UIViewController?) {
if let _viewController = viewController {
_viewController.willMoveToParentViewController(nil)
_viewController.view.removeFromSuperview()
_viewController.removeFromParentViewController()
}
}
func closeLeftNonAnimation(){
self.setCloseWindowLebel()
var finalXOrigin: CGFloat = self.leftMinOrigin()
var frame: CGRect = self.leftContainerView.frame;
frame.origin.x = finalXOrigin
self.leftContainerView.frame = frame
self.opacityView.layer.opacity = 0.0
self.mainContainerView.transform = CGAffineTransformMakeScale(1.0, 1.0)
self.removeShadow(self.leftContainerView)
self.enableContentInteraction()
}
func closeRightNonAnimation(){
self.setCloseWindowLebel()
var finalXOrigin: CGFloat = CGRectGetWidth(self.view.bounds)
var frame: CGRect = self.rightContainerView.frame
frame.origin.x = finalXOrigin
self.rightContainerView.frame = frame
self.opacityView.layer.opacity = 0.0
self.mainContainerView.transform = CGAffineTransformMakeScale(1.0, 1.0)
self.removeShadow(self.rightContainerView)
self.enableContentInteraction()
}
//pragma mark – UIGestureRecognizerDelegate
func gestureRecognizer(gestureRecognizer: UIGestureRecognizer, shouldReceiveTouch touch: UITouch) -> Bool {
var point: CGPoint = touch.locationInView(self.view)
if gestureRecognizer == self.leftPanGesture {
return self.slideLeftForGestureRecognizer(gestureRecognizer, point: point)
} else if gestureRecognizer == self.rightPanGesture {
return self.slideRightViewForGestureRecognizer(gestureRecognizer, withTouchPoint: point)
} else if gestureRecognizer == self.leftTapGetsture {
return self.isLeftOpen() && !self.isPointContainedWithinLeftRect(point)
} else if gestureRecognizer == self.rightTapGesture {
return self.isRightOpen() && !self.isPointContainedWithinRightRect(point)
}
return true
}
private func slideLeftForGestureRecognizer( gesture: UIGestureRecognizer, point:CGPoint) -> Bool{
return self.isLeftOpen() || self.options.panFromBezel && self.isLeftPointContainedWithinBezelRect(point)
}
private func isLeftPointContainedWithinBezelRect(point: CGPoint) -> Bool{
var leftBezelRect: CGRect = CGRectZero
var tempRect: CGRect = CGRectZero
var bezelWidth: CGFloat = self.options.leftBezelWidth
CGRectDivide(self.view.bounds, &leftBezelRect, &tempRect, bezelWidth, CGRectEdge.MinXEdge)
return CGRectContainsPoint(leftBezelRect, point)
}
private func isPointContainedWithinLeftRect(point: CGPoint) -> Bool {
return CGRectContainsPoint(self.leftContainerView.frame, point)
}
private func slideRightViewForGestureRecognizer(gesture: UIGestureRecognizer, withTouchPoint point: CGPoint) -> Bool {
return self.isRightOpen() || self.options.rightPanFromBezel && self.isRightPointContainedWithinBezelRect(point)
}
private func isRightPointContainedWithinBezelRect(point: CGPoint) -> Bool {
var rightBezelRect: CGRect = CGRectZero
var tempRect: CGRect = CGRectZero
//CGFloat bezelWidth = self.rightContainerView.frame.size.width;
var bezelWidth: CGFloat = CGRectGetWidth(self.view.bounds) - self.options.rightBezelWidth
CGRectDivide(self.view.bounds, &tempRect, &rightBezelRect, bezelWidth, CGRectEdge.MinXEdge)
return CGRectContainsPoint(rightBezelRect, point)
}
private func isPointContainedWithinRightRect(point: CGPoint) -> Bool {
return CGRectContainsPoint(self.rightContainerView.frame, point)
}
}
extension UIViewController {
func slideMenuController() -> SlideMenuController? {
var viewController: UIViewController? = self
while viewController != nil {
if viewController is SlideMenuController {
return viewController as? SlideMenuController
}
viewController = viewController?.parentViewController
}
return nil;
}
func addLeftBarButtonWithImage(buttonImage: UIImage) {
var leftButton: UIBarButtonItem = UIBarButtonItem(image: buttonImage, style: UIBarButtonItemStyle.Bordered, target: self, action: "toggleLeft")
self.navigationItem.leftBarButtonItem = leftButton;
}
func addRightBarButtonWithImage(buttonImage: UIImage) {
var rightButton: UIBarButtonItem = UIBarButtonItem(image: buttonImage, style: UIBarButtonItemStyle.Bordered, target: self, action: "toggleRight")
self.navigationItem.rightBarButtonItem = rightButton;
}
func toggleLeft() {
self.slideMenuController()?.toggleLeft()
}
func toggleRight() {
self.slideMenuController()?.toggleRight()
}
func openLeft() {
self.slideMenuController()?.openLeft()
}
func openRight() {
self.slideMenuController()?.openRight() }
func closeLeft() {
self.slideMenuController()?.closeLeft()
}
func closeRight() {
self.slideMenuController()?.closeRight()
}
// Please specify if you want menu gesuture give priority to than targetScrollView
func addPriorityToMenuGesuture(targetScrollView: UIScrollView) {
if let slideControlelr = self.slideMenuController() {
let recognizers = slideControlelr.view.gestureRecognizers
for recognizer in recognizers as! [UIGestureRecognizer] {
if recognizer is UIPanGestureRecognizer {
targetScrollView.panGestureRecognizer.requireGestureRecognizerToFail(recognizer)
}
}
}
}
}
| mit | 4c01ed5ca177e922970d9571402aa3c5 | 37.381057 | 153 | 0.64858 | 5.704698 | false | false | false | false |
ZeeQL/ZeeQL3 | Sources/ZeeQL/Control/QualifierParser.swift | 1 | 28501 | //
// QualifierParser.swift
// ZeeQL
//
// Created by Helge Hess on 16/02/2017.
// Copyright © 2017-2019 ZeeZide GmbH. All rights reserved.
//
// public extension Qualifier {}
// no static methods on protocols
public func qualifierWith(format: String, _ args: Any?...) -> Qualifier? {
let parser = QualifierParser(string: format, arguments: args)
return parser.parseQualifier()
}
/**
* Parses Qualifier objects from a char buffer. Qualifiers look like a
* SQL WHERE statement, but some special rules apply.
*
* ### KeyValueQualifier
* Example:
*
* lastname like 'h*'
*
* ### Comparison Operations
*
* - =
* - !=
* - <
* - ">"
* - =< <=
* - => >=
* - LIKE
* - IN (ComparisonOperation.CONTAINS) [TBD: a NOT IN array]
* - IS NULL / IS NOT NULL
* - custom identifiers, eg: 'hasPrefix:'
* - Note: you can use formats, eg: ("lastname %@ 'Duck'", "LIKE")
*
* ### Constants
*
* - numbers - 12345
* - strings - 'hello world' or "hello world"
* - boolean - true/false/YES/NO
* - null - NULL / null (no support for nil!)
* - casts - start with a '(', eg (Date)'2007-09-21'
*
* ### Qualifier Bindings
*
* Bindings are used to fill values into the qualifier at a later time. Each
* binding has a name which can be used multiple times in a single qualifier.
* The binding is represented as a QualifierVariable object once it got
* parsed.
*
* Example:
*
* lastname = $lastname AND firstname = $firstname
*
* Matching code:
*
* var q = Qualifier.parse("lastname = $lastname AND firstname = $firstname")
* q = q.qualifierWith(bindings: self)
*
* The q.qualifierWith(bindings:) method will ask 'self' for the
* 'lastname' and 'firstname' keys using KVC.
*
* ### Patterns
*
* You can embed patterns in a qualifier format, eg:
*
* lastname like %@
*
* The pattern is resolved during format parsing, in the above case the
* matching Java code would look like:
*
* let q = Qualifier.parse("lastname like %@", "Duck");
*
* (usually the argument will be some instance variable, eg one which is filled
* from a search field).
*
* There is no strict rule when to use Patterns and when to using Bindings.
* Usually bindings are more convenient to map to control elements (because
* the bindings dictionary can be filled conveniently using KVC).
*
* - %@ - use given value as-is
* - %s - convert value to String
* - %i / %d - convert value to Integer
* - %f - convert value to Double
* - %K - a key, this will result in a KeyComparisonQualifier
* - %% - to escape %
*
*
* #### True/False Qualifiers
* Those are sometimes useful in rules, they always match or fail:
*
* *true*
* *false*
*
* ### SQL Qualifiers
*
* To embed SQL in your qualifiers, you can use the `SQL[]`
* construct, eg:
*
* lastname = 'Duck' AND SQL[ EXISTS (SELECT 1 FROM permissions) ]
*
* A SQL qualifier can even include bindings. The qualifier is represented as
* a SQLQualifier object at runtime, which in turn is a sequence of 'parts'.
* Those parts are either QualifierVariable's or RawSQLValue's (those are
* output as-is by SQLExpression).
*/
open class QualifierParser {
open var log : ZeeQLLogger = globalZeeQLLogger
/* input */
let string : String
let args : [ Any? ]
/* processing status */
var idx : String.Index
var currentArgument : Int = 0
/* constructors */
public init(string: String, arguments: [ Any? ] = []) {
self.string = string
self.args = arguments
self.idx = self.string.startIndex
}
/* main entry */
public func parseQualifier() -> Qualifier? {
guard skipSpaces() else { return nil } // EOF
return parseCompoundQualifier()
}
/* parsing */
func parseOneQualifier() -> Qualifier? {
guard skipSpaces() else { return nil } // EOF
/* sub-qualifiers in parenthesis */
if match("(") { return parseCompoundQualifierInParenthesis() }
/* NOT qualifier */
if match(TOK_NOT) { return parseNotQualifier() }
/* raw SQL qualifier */
if match(TOK_SQL) { return parseRawSQLQualifier() }
/* special constant qualifiers */
if consumeIfMatch(TOK_STAR_TRUE) { return BooleanQualifier.trueQualifier }
if consumeIfMatch(TOK_STAR_FALSE) { return BooleanQualifier.falseQualifier }
return parseKeyBasedQualifier()
}
func nextNonNullStringArgument(_ _pat: String) -> String? {
guard currentArgument < args.count else {
addError("more format patterns than arguments")
return nil
}
let arg = args[currentArgument]
currentArgument += 1 /* consume */
/* process format spec */
let pidx = _pat.index(after: _pat.startIndex)
switch _pat[pidx] {
case "K", "s", "i", "d", "f", "@":
if let arg = arg {
return "\(arg)" // ... toString
}
else {
return "nil"
}
case "%":
addError("not yet supported: %%")
return nil
default:
addError("unknown string format specification: \(_pat)")
return nil
}
}
func parseKeyBasedQualifier() -> Qualifier? {
// TODO: we need to improve and consolidate the argument handling, but hey,
// it works ;-)
// Maybe we want to move it to the identifier parsing?
/* some identifier or keyword */
guard var id = parseIdentifier(onlyBreakOnSpace: false) else {
return nil /* found no ID, error */
}
/* process formats */
if id.count > 1 && id.hasPrefix("%") {
// the id itself is a format, eg: "%@ LIKE 'Hello*'"
guard let pid = nextNonNullStringArgument(id) else { return nil }
id = pid
}
if !skipSpaces() {
/* ok, it was just the ID. We treat this as a boolean kvqualifier,
* eg: "isArchived"
*/
return KeyValueQualifier(id, .EqualTo, true)
}
/* check whether the qualifier is closed, that is, whether we are bool */
if match(TOK_AND) || match(TOK_OR) || match(")") {
/* ok, it was just the ID. We treat this as a boolean kvqualifier,
* eg: "isArchived AND code > 10"
* "(code > 10 AND isArchived) AND is New"
*/
return KeyValueQualifier(id, .EqualTo, true)
}
/* OK, now we check for operations */
// can be 'IN' or '<' or 'has:'..
guard var operation = parseOperation() else {
/* ok, it was just the ID and some spaces, no operation. We treat this as
* a boolean kvqualifier, eg: "isArchived "
*/
return KeyValueQualifier(id, .EqualTo, true)
}
/* process formats */
if operation.count > 1 && operation.hasPrefix("%") {
// the operation is a pattern, eg: "value %@ 5", "<"
guard let pid = nextNonNullStringArgument(operation) else { return nil }
operation = pid
}
/* check for IS NULL and IS NOT NULL */
if operation == "IS" {
let saveIdx = idx
if skipSpaces() {
if consumeIfMatch(TOK_NOT) {
if skipSpaces() {
if consumeIfMatch(TOK_NULL) {
return KeyValueQualifier(id, .NotEqualTo, nil)
}
}
}
else if consumeIfMatch(TOK_NULL) {
return KeyValueQualifier(id, .EqualTo, nil)
}
}
/* did not match, restore pointer */
idx = saveIdx
}
// TBD: special support for "NOT IN" (do a regular IN, then wrap in NotQual)
/* and finally the right hand side (either id or value) */
guard skipSpaces() else {
addError("expected value/id after identifier and operation " +
"(op=\(operation), id=\(id))")
return nil /* EOF */
}
/* process variables ($name) */
if (match("$")) {
idx = string.index(after: idx) // consume $
guard let varId = parseIdentifier(onlyBreakOnSpace: false) else {
addError("expected variable identifier after '$'?!")
return nil /* EOF */
}
let op = ComparisonOperation(string: operation)
return KeyValueQualifier(id, op, QualifierVariable(key: varId))
}
/* process value arguments */
if (match("%")) {
/* Note: we do not support %%, and we do not support arbitrary
* strings, like "col_%K" or something like this
*/
idx = string.index(after: idx) // consume %
let fspec = string[idx]
idx = string.index(after: idx) // consume format spec char
/* retrieve argument */
guard currentArgument < args.count else {
addError("more format patterns than arguments")
return nil
}
let arg = args[currentArgument]
currentArgument += 1 /* consume */
/* convert argument */
switch fspec {
case "@":
return KeyValueQualifier(id, operation, arg)
case "s":
if let arg = arg as? String {
return KeyValueQualifier(id, operation, arg)
}
else if let arg = arg {
return KeyValueQualifier(id, operation, "\(arg)") // hm
}
else {
return KeyValueQualifier(id, .EqualTo, nil)
}
case "d", "i":
if let arg = arg as? Int {
return KeyValueQualifier(id, operation, arg)
}
else if let arg = arg {
return KeyValueQualifier(id, operation, Int("\(arg)")) // hm
}
else {
return KeyValueQualifier(id, .EqualTo, nil)
}
case "f":
if let arg = arg as? Double {
return KeyValueQualifier(id, operation, arg)
}
else if let arg = arg as? Int {
return KeyValueQualifier(id, operation, Double(arg))
}
else if let arg = arg {
return KeyValueQualifier(id, operation, Double("\(arg)")) // hm
}
else {
return KeyValueQualifier(id, .EqualTo, nil)
}
case "K":
if let arg = arg as? String {
return KeyComparisonQualifier(id, operation, arg)
}
else if let arg = arg {
return KeyComparisonQualifier(id, operation, "\(arg)") // hm
}
else {
addError("Argument for %K pattern is nil, needs to be a key!")
return nil
}
case "%":
addError("not yet supported: %%")
return nil
default:
addError("unknown format specification: %\(fspec)")
return nil
}
}
/* process constants */
if matchConstant() {
/* KeyValueQualifier */
let isIN = operation == "IN" || operation == "NOT IN"
let v = parseConstant(allowCast: !isIN /* allow cast */)
return KeyValueQualifier(id, operation, v)
}
/* process identifiers */
guard let rhs = parseIdentifier(onlyBreakOnSpace: false) else {
addError("expected value/id after identifier and operation?!")
return nil /* EOF */
}
return KeyComparisonQualifier(id, operation, rhs)
}
func parseNotQualifier() -> Qualifier? {
guard consumeIfMatch(TOK_NOT) else { return nil }
guard skipSpaces() else {
addError("missing qualifier after NOT!");
return nil /* ERROR */
}
guard let q = parseOneQualifier() else { return nil } /* parsing failed */
return q.not
}
func parseCompoundQualifierInParenthesis() -> Qualifier? {
guard consumeIfMatch("(") else { return nil } /* not in parenthesis */
guard skipSpaces() else {
addError("missing closing parenthesis!")
return nil /* ERROR */
}
/* parse qualifier */
guard let q = parseCompoundQualifier() else { return nil }
_ = skipSpaces()
if !consumeIfMatch(")") { /* be tolerant and keep the qualifier */
addError("missing closing parenthesis!")
}
return q
}
func buildCompoundQualifier(operation: String, qualifiers: [ Qualifier ])
-> Qualifier?
{
guard !qualifiers.isEmpty else { return nil }
if qualifiers.count == 1 { return qualifiers[0] }
switch operation {
case STOK_AND: return CompoundQualifier(qualifiers: qualifiers, op: .And)
case STOK_OR: return CompoundQualifier(qualifiers: qualifiers, op: .Or)
default:
/* Note: we could make this extensible */
addError("unknown compound operator: " + operation)
return nil
}
}
func parseCompoundQualifier() -> Qualifier? {
var qualifiers = [ Qualifier ]()
var lastCompoundOperator : String? = nil
while idx < string.endIndex {
guard let q = parseOneQualifier() else { return nil }
qualifiers.append(q)
guard skipSpaces() else { break } /* expected EOF */
/* check whether a closing paren is up front */
if match(")") { break } /* stop processing */
/* now check for AND or OR */
guard var compoundOperator = parseIdentifier(onlyBreakOnSpace: false)
else {
addError("could not parse compound operator, index: \(idx)")
break
}
/* process formats */
if compoundOperator.count > 1 && compoundOperator.hasPrefix("%") {
guard let s = nextNonNullStringArgument(compoundOperator)
else { return nil }
compoundOperator = s
}
guard skipSpaces() else {
addError("expected another qualifier after compound operator " +
"(op='\(compoundOperator)')")
break
}
if let lastCompoundOperator = lastCompoundOperator {
if compoundOperator != lastCompoundOperator {
/* operation changed, for example:
* a AND b AND c OR d OR e AND f
* will be parsed as:
* ((a AND b AND c) OR d OR e) AND f
*/
let q = buildCompoundQualifier(operation: lastCompoundOperator,
qualifiers: qualifiers)
qualifiers.removeAll()
if let q = q {
qualifiers.append(q)
}
}
}
lastCompoundOperator = compoundOperator;
}
return buildCompoundQualifier(operation: lastCompoundOperator ?? "AND",
qualifiers: qualifiers)
}
/**
* parse something like this:
*
* SQL[select abc WHERE date_id = $dateId]
*
* into:
*
* "select abc WHERE date_id ="
*
* Note that the SQL strings are converted into RawSQLValue objects so
* that they do not get quoted as SQL strings during SQL generation.
*/
func parseRawSQLQualifier() -> Qualifier? {
guard consumeIfMatch(TOK_SQL) else { return nil }
var parts = Array<SQLQualifier.Part>()
var sql = ""
var pidx = idx
while pidx < string.endIndex {
if string[pidx] == "]" {
idx = string.index(after: pidx) /* consume ] */
break
}
else if string[pidx] == "$" {
if !sql.isEmpty {
parts.append(.RawSQLValue(sql))
sql.removeAll() /* reset char buffer */
}
idx = string.index(after: pidx) /* skip "$" */
let varName = parseIdentifier(onlyBreakOnSpace: false)
pidx = string.index(before: idx)
/* will get bumped by next loop iteration */
if let varName = varName {
parts.append(.QualifierVariable(varName))
}
else {
addError("could not parse SQL qualifier variable?!")
}
}
else {
/* regular char */
sql.append(string[pidx])
}
pidx = string.index(after: pidx)
}
if !sql.isEmpty {
parts.append(.RawSQLValue(sql))
}
return SQLQualifier(parts: parts)
}
/**
* Parse an identifier. Identifiers do not start with numbers or spaces, they
* are at least on char long.
*
* @param _onlyBreakOnSpace - read ID until a space is encountered
* @return String containing the ID or if not could be found
*/
func parseIdentifier(onlyBreakOnSpace: Bool) -> String? {
guard idx < string.endIndex else { return nil } // EOF
guard !_isDigit(string[idx]) else { return nil }
/* identifiers never start with a digit */
guard !_isSpace(string[idx]) else { return nil } /* nor with a space */
/* we are extremely tolerant here, everything is allowed as long as it
* starts w/o a digit. processing ends at the next space.
*/
var pidx = string.index(after: idx)
while pidx < string.endIndex {
if onlyBreakOnSpace {
if _isSpace(string[pidx]) {
break
}
}
else if _isIdBreakChar(string[pidx]) { /* Note: this includes spaces */
break
}
pidx = string.index(after: pidx)
}
/* Note: len==0 cannot happen, caught above */
let id = string[idx..<pidx]
idx = pidx /* consume */
return String(id)
}
/**
* Parses qualifier operations. If none matches, parseIdentifier is called.
*/
func parseOperation() -> String? {
guard canLA(2) else { return nil }
if string[idx] == "=" {
idx = string.index(after: idx)
if string[idx] == ">" {
idx = string.index(after: idx)
return "=>"
}
if string[idx] == "<" {
idx = string.index(after: idx)
return "=<"
}
return "="
}
if string[idx] == "!" && string[string.index(after: idx)] == "=" {
idx = string.index(idx, offsetBy: 2)
return "!="
}
if string[idx] == "<" {
idx = string.index(after: idx)
if string[idx] == "=" {
idx = string.index(after: idx)
return "=<"
}
if string[idx] == ">" {
idx = string.index(after: idx)
return "<>"
}
return "<"
}
if string[idx] == ">" {
idx = string.index(after: idx)
if string[idx] == "=" {
idx = string.index(after: idx)
return "=>"
}
if string[idx] == "<" {
idx = string.index(after: idx)
return "<>"
}
return ">"
}
// TBD: support IN and => NOT IN
// TODO: better an own parser? hm, yes.
// the following stuff parses things like hasPrefix:, but also IN!
return parseIdentifier(onlyBreakOnSpace: true)
}
func matchConstant() -> Bool {
guard idx < string.endIndex else { return false }
if string[idx] == "(" {
guard skipSpaces() else { return false } // TODO: bug? skip consumes
return true // no further checks for: ID ')'
}
if _isDigit(string[idx]) { return true }
if string[idx] == "'" { return true }
if string[idx] == "\"" { return true } // TODO: would be an ID in SQL
if match(TOK_TRUE) { return true }
if match(TOK_FALSE) { return true }
if match(TOK_NULL) { return true }
if match(TOK_null) { return true }
if match(TOK_nil) { return true }
if match(TOK_YES) { return true }
if match(TOK_NO) { return true }
return false
}
func matchCast() -> Bool {
guard canLA(2) else { return false } /* at least (a) */
if (string[idx] == "(") {
guard skipSpaces() else { return false } // TODO: bug? skip consumes
return true // no further checks for: ID ')'
}
return false
}
func parseCast() -> String? {
guard canLA(2) else { return nil } /* at least (a) */
guard string[idx] == "(" else { return nil }
guard skipSpaces() else {
addError("expected class cast identifier after parenthesis!");
return nil;
}
guard let castClass = parseIdentifier(onlyBreakOnSpace: false /* on all */)
else {
addError("expected class cast identifier after parenthesis!");
return nil
}
guard skipSpaces() else {
addError("expected closing parenthesis after class cast!");
return nil
}
guard consumeIfMatch(")") else {
addError("expected closing parenthesis after class cast!");
return nil
}
return castClass
}
/**
* This parses:
*
* - single quoted strings
* - double quoted strings
* - numbers
* - true/false, YES/NO
* - null/NULL
*
* The constant can be prefixed with a cast, eg:
*
* (int)"383"
*
* But the casts are not resolved yet ...
*/
func _parseConstant(allowCast: Bool) -> Constant? { // TODO
let castClass = allowCast ? parseCast() : nil
let v : Constant?
if string[idx] == "\'" {
if let s = parseQuotedString() { v = .String(s) } else { v = nil }
}
else if string[idx] == "\"" { // TODO: could be a SQL id
if let s = parseQuotedString() { v = .String(s) } else { v = nil }
}
else if _isDigit(string[idx]) {
if let n = parseNumber() {
switch n {
case .Int (let i): v = .Int(i)
case .Double(let i): v = .Double(i)
}
}
else { v = nil }
}
else if consumeIfMatch(TOK_TRUE) || consumeIfMatch(TOK_YES) {
v = .Bool(true)
}
else if consumeIfMatch(TOK_FALSE) || consumeIfMatch(TOK_NO) {
v = .Bool(false)
}
else if match("(") {
/* a plist array after an IN (otherwise a CAST is handled above!) */
addError("plist array values after IN are not yet supported!")
v = nil
}
else if consumeIfMatch(TOK_NULL) {
return nil // do not apply casts for nil
}
else if consumeIfMatch(TOK_null) {
return nil // do not apply casts for nil
}
else if consumeIfMatch(TOK_nil) {
return nil // do not apply casts for nil
}
else {
return nil // hm, can't distinguish between this and nil => match..
}
if let castClass = castClass {
// TBD: another option might be to support property lists, eg:
// code IN ( 'a', 'b', 'c' )
// maybe distinguish by checking for an ID?
// TODO: handle casts, eg (Date)'2006-06-10'
log.warn("not handling cast to '\(castClass)', value: \(v as Optional)")
}
return v
}
enum Constant {
case String(String)
case Int (Int)
case Double(Double)
case Bool (Bool)
var asAny : Any {
switch self {
case .String(let v): return v
case .Int (let v): return v
case .Double(let v): return v
case .Bool (let v): return v
}
}
}
func parseConstant(allowCast: Bool) -> Any? {
guard let c = _parseConstant(allowCast: allowCast) else { return nil }
return c.asAny
}
func parseQuotedString() -> String? {
let quoteChar = string[idx]
/* a quoted string */
var pos = string.index(after: idx) /* skip quote */
let startPos = pos
guard startPos != string.endIndex else { return nil }
var containsEscaped = false
/* loop until closing quote */
while (string[pos] != quoteChar) && (pos < string.endIndex) {
if string[pos] == "\\" {
containsEscaped = true
pos = string.index(after: pos) /* skip following char */
if pos == string.endIndex {
addError("escape in quoted string not finished!")
return nil
}
}
pos = string.index(after: pos)
}
if pos == string.endIndex { /* syntax error, quote not closed */
idx = pos
addError("quoted string not closed (expected '\(quoteChar)')")
return nil
}
idx = string.index(after: pos) /* skip closing quote, consume */
if startPos == pos { /* empty string */
return ""
}
if containsEscaped {
// TODO: implement unescaping in quoted strings
log.error("unescaping not implemented!")
}
return String(string[startPos..<pos])
}
enum Number {
case Int(Int)
case Double(Double)
}
func parseNumber() -> Number? { // TODO: not just int
guard idx < string.endIndex else { return nil } // EOF
guard _isDigit(string[idx]) || string[idx] == "-" else { return nil }
/* we are extremely tolerant here, almost everything is allowed ... */
var pidx = string.index(after: idx)
while pidx < string.endIndex {
if _isIdBreakChar(string[pidx]) || string[pidx] == ")" { break }
pidx = string.index(after: pidx)
}
/* Note: len==0 cannot happen, caught above */
let numstr = string[idx..<pidx]
idx = pidx // consume
if numstr.contains(".") {
guard let v = Double(numstr) else {
addError("failed to parse number: '" + numstr + "'");
return nil
}
return Number.Double(v)
}
else {
guard let v = Int(numstr) else {
addError("failed to parse number: '" + numstr + "'");
return nil
}
return Number.Int(v)
}
}
func addError(_ _reason: String) {
// TODO: generate some exception
log.error(_reason)
}
/* core parsing */
final func _isDigit(_ c: Character) -> Bool {
switch c {
case "0", "1", "2", "3", "4", "5", "6", "7", "8", "9": return true
default: return false
}
}
final func _isSpace(_ c: Character) -> Bool {
switch c {
case " ", "\t", "\n", "\r": return true
default: return false
}
}
final func _isIdBreakChar(_ c: Character) -> Bool {
switch c {
case " ", "\t", "\n", "\r", "<", ">", "=", "*", "/", "+",
"-", "(", ")", "]", "!": /* eg NSFileName!="index.html" */
return true
default:
return false
}
}
final func skipSpaces() -> Bool {
while idx < string.endIndex {
if !_isSpace(string[idx]) {
return true;
}
idx = string.index(after: idx)
}
return idx < string.endIndex
}
final func la(_ i : Int) -> Character? {
guard canLA(i) else { return nil }
return string[string.index(idx, offsetBy: i)]
}
final func match(_ tok: [ Character ]) -> Bool {
guard canLA(tok.count) else { return false }
var midx = idx
for c in tok {
guard c == string[midx] else { return false }
midx = string.index(after: midx)
}
return true
}
/**
* Returns true if the current parsing position matches the char. This does
* NOT consume the char (use consumeIfMatch for that).
* Example:
*
* if (match(")")) return ...</pre>
*
*/
func match(_ c: Character) -> Bool {
guard idx < string.endIndex else { return false }
return string[idx] == c
}
func consumeIfMatch(_ tok: [ Character ]) -> Bool {
guard match(tok) else { return false }
idx = string.index(idx, offsetBy: tok.count)
return true
}
func consumeIfMatch(_ c: Character) -> Bool {
guard match(c) else { return false }
idx = string.index(after: idx);
return true
}
final func canLA(_ count : Int) -> Bool {
return string.canLA(count, startIndex: idx)
}
/* tokens */
let STOK_AND = "AND"
let STOK_OR = "OR"
let TOK_NOT : [ Character ] = [ "N", "O", "T" ]
let TOK_NULL : [ Character ] = [ "N", "U", "L", "L" ]
let TOK_null : [ Character ] = [ "n", "u", "l", "l" ]
let TOK_nil : [ Character ] = [ "n", "i", "l" ]
let TOK_TRUE : [ Character ] = [ "t", "r", "u", "e" ]
let TOK_FALSE : [ Character ] = [ "f", "a", "l", "s", "e" ]
let TOK_YES : [ Character ] = [ "Y", "E", "S" ]
let TOK_NO : [ Character ] = [ "N", "O" ]
let TOK_SQL : [ Character ] = [ "S", "Q", "L", "[" ]
let TOK_AND : [ Character ] = [ "A", "N", "D" ]
let TOK_OR : [ Character ] = [ "O", "R" ]
let TOK_STAR_TRUE : [ Character ] = [ "*", "t", "r", "u", "e", "*" ]
let TOK_STAR_FALSE : [ Character ] = [ "*", "f", "a", "l", "s", "e", "*" ]
}
extension String {
func canLA(_ count: Int, startIndex: Index) -> Bool {
if startIndex == endIndex { return false }
guard count != 0 else { return true } // can always not lookahead
// this asserts on overflow: string.index(idx, offsetBy: count), so it is
// no good for range-checks.
// TBD: is there a betta way?
var toGo = count
var cursor = startIndex
while cursor != endIndex {
toGo -= 1
if toGo == 0 { return true }
cursor = index(after: cursor)
}
return toGo == 0
}
}
| apache-2.0 | 8015d02b8747eb82b4e7e70edaea7a6d | 27.358209 | 80 | 0.55986 | 4.000561 | false | false | false | false |
lukevanin/SwiftPromise | SwiftPromise/Result.swift | 1 | 2675 | //
// Result.swift
// SwiftPromise
//
// Created by Luke Van In on 2016/07/05.
// Copyright © 2016 Luke Van In. All rights reserved.
//
import Foundation
public enum Result<T> {
case Success(T)
case Failure(ErrorProtocol)
public var success: Bool {
switch self {
case .Success(_):
return true
default:
return false
}
}
public var value: T? {
switch self {
case .Success(let value):
return value
default:
return nil
}
}
public var failure: Bool {
return !success
}
public var error: ErrorProtocol? {
switch self {
case .Failure(let error):
return error
default:
return nil
}
}
public init(_ error: ErrorProtocol) {
self = .Failure(error)
}
public init(_ value: T) {
self = .Success(value)
}
public init( _ f: @noescape() throws -> T) {
do {
self = .Success(try f())
}
catch let e {
self = .Failure(e)
}
}
}
extension Result {
public func map<P>(f: (T) -> P) -> Result<P> {
switch self {
case .Success(let value):
return .Success(f(value))
case .Failure(let error):
return .Failure(error)
}
}
public func map<P>(f: (T) throws -> P) -> Result<P> {
switch self {
case .Success(let value):
do {
return .Success(try f(value))
}
catch let error {
return .Failure(error)
}
case .Failure(let error):
return .Failure(error)
}
}
public func map<P>(f: (T, error: NSErrorPointer) -> P?) -> Result<P> {
switch self {
case .Success(let value):
var error: NSError?
if let p = f(value, error: &error) {
return .Success(p)
}
else {
return .Failure(error!)
}
case .Failure(let error):
return .Failure(error)
}
}
}
extension Result {
public func flatMap<P>(f: (T) -> Result<P>) -> Result<P> {
switch self {
case .Success(let value):
return f(value)
case .Failure(let error):
return .Failure(error)
}
}
}
extension Result {
public func realize() throws -> T {
switch self {
case .Success(let value):
return value
case .Failure(let error):
throw error
}
}
}
| mit | 78fca0ed054148e2ed25099249c70fa7 | 15.304878 | 74 | 0.466343 | 4.271565 | false | false | false | false |
nathawes/swift | stdlib/public/Darwin/Foundation/Scanner.swift | 9 | 9254 | // Copyright (c) 2019 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 CharacterSet {
fileprivate func contains(_ character: Character) -> Bool {
return character.unicodeScalars.allSatisfy(self.contains(_:))
}
}
// -----
@available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *)
extension Scanner {
public enum NumberRepresentation {
case decimal // See the %d, %f and %F format conversions.
case hexadecimal // See the %x, %X, %a and %A format conversions. For integers, a leading 0x or 0X is optional; for floating-point numbers, it is required.
}
public var currentIndex: String.Index {
get {
let string = self.string
var index = string._toUTF16Index(scanLocation)
var delta = 0
while index != string.endIndex && index.samePosition(in: string) == nil {
delta += 1
index = string._toUTF16Index(scanLocation + delta)
}
return index
}
set { scanLocation = string._toUTF16Offset(newValue) }
}
fileprivate func _scan<Integer: FixedWidthInteger>
(representation: NumberRepresentation,
scanDecimal: (UnsafeMutablePointer<Integer>?) -> Bool,
scanHexadecimal: (UnsafeMutablePointer<Integer>?) -> Bool) -> Integer? {
var value: Integer = .max
switch representation {
case .decimal: guard scanDecimal(&value) else { return nil }
case .hexadecimal: guard scanHexadecimal(&value) else { return nil }
}
return value
}
fileprivate func _scan<FloatingPoint: BinaryFloatingPoint>
(representation: NumberRepresentation,
scanDecimal: (UnsafeMutablePointer<FloatingPoint>?) -> Bool,
scanHexadecimal: (UnsafeMutablePointer<FloatingPoint>?) -> Bool) -> FloatingPoint? {
var value: FloatingPoint = .greatestFiniteMagnitude
switch representation {
case .decimal: guard scanDecimal(&value) else { return nil }
case .hexadecimal: guard scanHexadecimal(&value) else { return nil }
}
return value
}
fileprivate func _scan<Integer: FixedWidthInteger, OverflowingHexadecimalInteger: FixedWidthInteger & UnsignedInteger>
(representation: NumberRepresentation,
scanDecimal: (UnsafeMutablePointer<Integer>?) -> Bool,
overflowingScanHexadecimal: (UnsafeMutablePointer<OverflowingHexadecimalInteger>?) -> Bool) -> Integer? {
return _scan(representation: representation, scanDecimal: scanDecimal, scanHexadecimal: { (pointer) -> Bool in
var unsignedValue: OverflowingHexadecimalInteger = .max
guard overflowingScanHexadecimal(&unsignedValue) else { return false }
if unsignedValue <= Integer.max {
pointer?.pointee = Integer(unsignedValue)
}
return true
})
}
public func scanInt(representation: NumberRepresentation = .decimal) -> Int? {
#if arch(x86_64) || arch(arm64) || arch(s390x) || arch(powerpc64) || arch(powerpc64le)
if let value = scanInt64(representation: representation) {
return Int(value)
}
#elseif arch(i386) || arch(arm)
if let value = scanInt32(representation: representation) {
return Int(value)
}
#else
#error("This architecture isn't known. Add it to the 32-bit or 64-bit line; if the machine word isn't either of those, you need to implement appropriate scanning and handle the potential overflow here.")
#endif
return nil
}
public func scanInt32(representation: NumberRepresentation = .decimal) -> Int32? {
return _scan(representation: representation, scanDecimal: self.scanInt32(_:), overflowingScanHexadecimal: self.scanHexInt32(_:))
}
public func scanInt64(representation: NumberRepresentation = .decimal) -> Int64? {
return _scan(representation: representation, scanDecimal: self.scanInt64(_:), overflowingScanHexadecimal: self.scanHexInt64(_:))
}
public func scanUInt64(representation: NumberRepresentation = .decimal) -> UInt64? {
return _scan(representation: representation, scanDecimal: self.scanUnsignedLongLong(_:), scanHexadecimal: self.scanHexInt64(_:))
}
public func scanFloat(representation: NumberRepresentation = .decimal) -> Float? {
return _scan(representation: representation, scanDecimal: self.scanFloat(_:), scanHexadecimal: self.scanHexFloat(_:))
}
public func scanDouble(representation: NumberRepresentation = .decimal) -> Double? {
return _scan(representation: representation, scanDecimal: self.scanDouble(_:), scanHexadecimal: self.scanHexDouble(_:))
}
public func scanDecimal() -> Decimal? {
var value: Decimal = 0
guard scanDecimal(&value) else { return nil }
return value
}
fileprivate var _currentIndexAfterSkipping: String.Index {
guard let skips = charactersToBeSkipped else { return currentIndex }
let index = string[currentIndex...].firstIndex(where: { !skips.contains($0) })
return index ?? string.endIndex
}
public func scanString(_ searchString: String) -> String? {
let currentIndex = _currentIndexAfterSkipping
guard let substringEnd = string.index(currentIndex, offsetBy: searchString.count, limitedBy: string.endIndex) else { return nil }
if string.compare(searchString, options: self.caseSensitive ? [] : .caseInsensitive, range: currentIndex ..< substringEnd, locale: self.locale as? Locale) == .orderedSame {
let it = string[currentIndex ..< substringEnd]
self.currentIndex = substringEnd
return String(it)
} else {
return nil
}
}
public func scanCharacters(from set: CharacterSet) -> String? {
let currentIndex = _currentIndexAfterSkipping
let substringEnd = string[currentIndex...].firstIndex(where: { !set.contains($0) }) ?? string.endIndex
guard currentIndex != substringEnd else { return nil }
let substring = string[currentIndex ..< substringEnd]
self.currentIndex = substringEnd
return String(substring)
}
public func scanUpToString(_ substring: String) -> String? {
guard !substring.isEmpty else { return nil }
let string = self.string
let startIndex = _currentIndexAfterSkipping
var beginningOfNewString = string.endIndex
var currentSearchIndex = startIndex
repeat {
guard let range = string.range(of: substring, options: self.caseSensitive ? [] : .caseInsensitive, range: currentSearchIndex ..< string.endIndex, locale: self.locale as? Locale) else {
// If the string isn't found at all, it means it's not in the string. Just take everything to the end.
beginningOfNewString = string.endIndex
break
}
// range(of:…) can return partial grapheme ranges when dealing with emoji.
// Make sure we take a range only if it doesn't split a grapheme in the string.
if let maybeBeginning = range.lowerBound.samePosition(in: string),
range.upperBound.samePosition(in: string) != nil {
beginningOfNewString = maybeBeginning
break
}
// If we got here, we need to search again starting from just after the location we found.
currentSearchIndex = range.upperBound
} while beginningOfNewString == string.endIndex && currentSearchIndex < string.endIndex
guard startIndex != beginningOfNewString else { return nil }
let foundSubstring = string[startIndex ..< beginningOfNewString]
self.currentIndex = beginningOfNewString
return String(foundSubstring)
}
public func scanUpToCharacters(from set: CharacterSet) -> String? {
let currentIndex = _currentIndexAfterSkipping
let string = self.string
let firstCharacterInSet = string[currentIndex...].firstIndex(where: { set.contains($0) }) ?? string.endIndex
guard currentIndex != firstCharacterInSet else { return nil }
self.currentIndex = firstCharacterInSet
return String(string[currentIndex ..< firstCharacterInSet])
}
public func scanCharacter() -> Character? {
let currentIndex = _currentIndexAfterSkipping
let string = self.string
guard currentIndex != string.endIndex else { return nil }
let character = string[currentIndex]
self.currentIndex = string.index(after: currentIndex)
return character
}
}
| apache-2.0 | 3b7fc3e2f019f22538f1bb28a464f997 | 42.43662 | 207 | 0.639754 | 5.154318 | false | false | false | false |
stripysock/SwiftGen | SwiftGen.playground/Pages/Colors-Demo.xcplaygroundpage/Contents.swift | 1 | 1939 | //: #### Other pages
//:
//: * [Demo for `swiftgen strings`](Strings-Demo)
//: * [Demo for `swiftgen images`](Images-Demo)
//: * [Demo for `swiftgen storyboards`](Storyboards-Demo)
//: * Demo for `swiftgen colors`
import UIKit
//: #### Example of code generated by swiftgen-colors
// Generated using SwiftGen, by O.Halligon — https://github.com/AliSoftware/SwiftGen
import UIKit
extension UIColor {
convenience init(rgbaValue: UInt32) {
let red = CGFloat((rgbaValue >> 24) & 0xff) / 255.0
let green = CGFloat((rgbaValue >> 16) & 0xff) / 255.0
let blue = CGFloat((rgbaValue >> 8) & 0xff) / 255.0
let alpha = CGFloat((rgbaValue ) & 0xff) / 255.0
self.init(red: red, green: green, blue: blue, alpha: alpha)
}
}
extension UIColor {
enum Name : UInt32 {
/// <span style="display:block;width:3em;height:2em;border:1px solid black;background:#ffffff"></span>
/// Alpha: 80% <br/> (0xffffffcc)
case Translucent = 0xffffffcc
/// <span style="display:block;width:3em;height:2em;border:1px solid black;background:#339666"></span>
/// Alpha: 100% <br/> (0x339666ff)
case ArticleBody = 0x339666ff
/// <span style="display:block;width:3em;height:2em;border:1px solid black;background:#ff66cc"></span>
/// Alpha: 100% <br/> (0xff66ccff)
case Cyan = 0xff66ccff
/// <span style="display:block;width:3em;height:2em;border:1px solid black;background:#33fe66"></span>
/// Alpha: 100% <br/> (0x33fe66ff)
case ArticleTitle = 0x33fe66ff
}
convenience init(named name: Name) {
self.init(rgbaValue: name.rawValue)
}
}
//: #### Usage Example
UIColor(named: .ArticleTitle)
UIColor(named: .ArticleBody)
UIColor(named: .ArticleBody)
UIColor(named: .Translucent)
/* Only possible if you used `enumBuilder.build(generateStringInit: true)` to generate the enum */
//let orange = UIColor(hexString: "#ffcc88")
let lightGreen = UIColor(rgbaValue: 0x00ff88ff)
| mit | 263595ee107ec35f4116d3446cd46ffc | 31.830508 | 106 | 0.670625 | 3.311111 | false | false | false | false |
jopamer/swift | stdlib/public/core/Set.swift | 1 | 127482 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2018 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
//===--- APIs unique to Set<Element> --------------------------------------===//
/// An unordered collection of unique elements.
///
/// You use a set instead of an array when you need to test efficiently for
/// membership and you aren't concerned with the order of the elements in the
/// collection, or when you need to ensure that each element appears only once
/// in a collection.
///
/// You can create a set with any element type that conforms to the `Hashable`
/// protocol. By default, most types in the standard library are hashable,
/// including strings, numeric and Boolean types, enumeration cases without
/// associated values, and even sets themselves.
///
/// Swift makes it as easy to create a new set as to create a new array. Simply
/// assign an array literal to a variable or constant with the `Set` type
/// specified.
///
/// let ingredients: Set = ["cocoa beans", "sugar", "cocoa butter", "salt"]
/// if ingredients.contains("sugar") {
/// print("No thanks, too sweet.")
/// }
/// // Prints "No thanks, too sweet."
///
/// Set Operations
/// ==============
///
/// Sets provide a suite of mathematical set operations. For example, you can
/// efficiently test a set for membership of an element or check its
/// intersection with another set:
///
/// - Use the `contains(_:)` method to test whether a set contains a specific
/// element.
/// - Use the "equal to" operator (`==`) to test whether two sets contain the
/// same elements.
/// - Use the `isSubset(of:)` method to test whether a set contains all the
/// elements of another set or sequence.
/// - Use the `isSuperset(of:)` method to test whether all elements of a set
/// are contained in another set or sequence.
/// - Use the `isStrictSubset(of:)` and `isStrictSuperset(of:)` methods to test
/// whether a set is a subset or superset of, but not equal to, another set.
/// - Use the `isDisjoint(with:)` method to test whether a set has any elements
/// in common with another set.
///
/// You can also combine, exclude, or subtract the elements of two sets:
///
/// - Use the `union(_:)` method to create a new set with the elements of a set
/// and another set or sequence.
/// - Use the `intersection(_:)` method to create a new set with only the
/// elements common to a set and another set or sequence.
/// - Use the `symmetricDifference(_:)` method to create a new set with the
/// elements that are in either a set or another set or sequence, but not in
/// both.
/// - Use the `subtracting(_:)` method to create a new set with the elements of
/// a set that are not also in another set or sequence.
///
/// You can modify a set in place by using these methods' mutating
/// counterparts: `formUnion(_:)`, `formIntersection(_:)`,
/// `formSymmetricDifference(_:)`, and `subtract(_:)`.
///
/// Set operations are not limited to use with other sets. Instead, you can
/// perform set operations with another set, an array, or any other sequence
/// type.
///
/// var primes: Set = [2, 3, 5, 7]
///
/// // Tests whether primes is a subset of a Range<Int>
/// print(primes.isSubset(of: 0..<10))
/// // Prints "true"
///
/// // Performs an intersection with an Array<Int>
/// let favoriteNumbers = [5, 7, 15, 21]
/// print(primes.intersection(favoriteNumbers))
/// // Prints "[5, 7]"
///
/// Sequence and Collection Operations
/// ==================================
///
/// In addition to the `Set` type's set operations, you can use any nonmutating
/// sequence or collection methods with a set.
///
/// if primes.isEmpty {
/// print("No primes!")
/// } else {
/// print("We have \(primes.count) primes.")
/// }
/// // Prints "We have 4 primes."
///
/// let primesSum = primes.reduce(0, +)
/// // 'primesSum' == 17
///
/// let primeStrings = primes.sorted().map(String.init)
/// // 'primeStrings' == ["2", "3", "5", "7"]
///
/// You can iterate through a set's unordered elements with a `for`-`in` loop.
///
/// for number in primes {
/// print(number)
/// }
/// // Prints "5"
/// // Prints "7"
/// // Prints "2"
/// // Prints "3"
///
/// Many sequence and collection operations return an array or a type-erasing
/// collection wrapper instead of a set. To restore efficient set operations,
/// create a new set from the result.
///
/// let morePrimes = primes.union([11, 13, 17, 19])
///
/// let laterPrimes = morePrimes.filter { $0 > 10 }
/// // 'laterPrimes' is of type Array<Int>
///
/// let laterPrimesSet = Set(morePrimes.filter { $0 > 10 })
/// // 'laterPrimesSet' is of type Set<Int>
///
/// Bridging Between Set and NSSet
/// ==============================
///
/// You can bridge between `Set` and `NSSet` using the `as` operator. For
/// bridging to be possible, the `Element` type of a set must be a class, an
/// `@objc` protocol (a protocol imported from Objective-C or marked with the
/// `@objc` attribute), or a type that bridges to a Foundation type.
///
/// Bridging from `Set` to `NSSet` always takes O(1) time and space. When the
/// set's `Element` type is neither a class nor an `@objc` protocol, any
/// required bridging of elements occurs at the first access of each element,
/// so the first operation that uses the contents of the set (for example, a
/// membership test) can take O(*n*).
///
/// Bridging from `NSSet` to `Set` first calls the `copy(with:)` method
/// (`- copyWithZone:` in Objective-C) on the set to get an immutable copy and
/// then performs additional Swift bookkeeping work that takes O(1) time. For
/// instances of `NSSet` that are already immutable, `copy(with:)` returns the
/// same set in constant time; otherwise, the copying performance is
/// unspecified. The instances of `NSSet` and `Set` share buffer using the
/// same copy-on-write optimization that is used when two instances of `Set`
/// share buffer.
@_fixed_layout
public struct Set<Element: Hashable> {
@usableFromInline
internal typealias _VariantBuffer = _VariantSetBuffer<Element>
@usableFromInline
internal typealias _NativeBuffer = _NativeSetBuffer<Element>
@usableFromInline
internal var _variantBuffer: _VariantBuffer
}
extension Set {
/// Creates an empty set with preallocated space for at least the specified
/// number of elements.
///
/// Use this initializer to avoid intermediate reallocations of a set's
/// storage buffer when you know how many elements you'll insert into the set
/// after creation.
///
/// - Parameter minimumCapacity: The minimum number of elements that the
/// newly created set should be able to store without reallocating its
/// storage buffer.
@inlinable // FIXME(sil-serialize-all)
public init(minimumCapacity: Int) {
_variantBuffer =
_VariantBuffer.native(
_NativeBuffer(minimumCapacity: minimumCapacity))
}
/// Private initializer.
@inlinable // FIXME(sil-serialize-all)
internal init(_nativeBuffer: _NativeSetBuffer<Element>) {
_variantBuffer = _VariantBuffer.native(_nativeBuffer)
}
//
// All APIs below should dispatch to `_variantBuffer`, without doing any
// additional processing.
//
#if _runtime(_ObjC)
/// Private initializer used for bridging.
///
/// Only use this initializer when both conditions are true:
///
/// * it is statically known that the given `NSSet` is immutable;
/// * `Element` is bridged verbatim to Objective-C (i.e.,
/// is a reference type).
@inlinable // FIXME(sil-serialize-all)
public init(_immutableCocoaSet: _NSSet) {
_sanityCheck(_isBridgedVerbatimToObjectiveC(Element.self),
"Set can be backed by NSSet _variantBuffer only when the member type can be bridged verbatim to Objective-C")
_variantBuffer = _VariantSetBuffer.cocoa(
_CocoaSetBuffer(cocoaSet: _immutableCocoaSet))
}
#endif
}
extension Set: ExpressibleByArrayLiteral {
//
// `ExpressibleByArrayLiteral` conformance
//
/// Creates a set containing the elements of the given array literal.
///
/// Do not call this initializer directly. It is used by the compiler when
/// you use an array literal. Instead, create a new set using an array
/// literal as its value by enclosing a comma-separated list of values in
/// square brackets. You can use an array literal anywhere a set is expected
/// by the type context.
///
/// Here, a set of strings is created from an array literal holding only
/// strings.
///
/// let ingredients: Set = ["cocoa beans", "sugar", "cocoa butter", "salt"]
/// if ingredients.isSuperset(of: ["sugar", "salt"]) {
/// print("Whatever it is, it's bound to be delicious!")
/// }
/// // Prints "Whatever it is, it's bound to be delicious!"
///
/// - Parameter elements: A variadic list of elements of the new set.
@inlinable // FIXME(sil-serialize-all)
public init(arrayLiteral elements: Element...) {
self.init(_nativeBuffer: _NativeSetBuffer.fromArray(elements))
}
}
extension Set: Sequence {
/// Returns an iterator over the members of the set.
@inlinable // FIXME(sil-serialize-all)
@inline(__always)
public func makeIterator() -> SetIterator<Element> {
return _variantBuffer.makeIterator()
}
/// Returns a Boolean value that indicates whether the given element exists
/// in the set.
///
/// This example uses the `contains(_:)` method to test whether an integer is
/// a member of a set of prime numbers.
///
/// let primes: Set = [2, 3, 5, 7]
/// let x = 5
/// if primes.contains(x) {
/// print("\(x) is prime!")
/// } else {
/// print("\(x). Not prime.")
/// }
/// // Prints "5 is prime!"
///
/// - Parameter member: An element to look for in the set.
/// - Returns: `true` if `member` exists in the set; otherwise, `false`.
///
/// - Complexity: O(1)
@inlinable // FIXME(sil-serialize-all)
public func contains(_ member: Element) -> Bool {
return _variantBuffer.maybeGet(member) != nil
}
@inlinable // FIXME(sil-serialize-all)
public func _customContainsEquatableElement(_ member: Element) -> Bool? {
return contains(member)
}
}
// This is not quite Sequence.filter, because that returns [Element], not Self
// (RangeReplaceableCollection.filter returns Self, but Set isn't an RRC)
extension Set {
/// Returns a new set containing the elements of the set that satisfy the
/// given predicate.
///
/// In this example, `filter(_:)` is used to include only names shorter than
/// five characters.
///
/// let cast: Set = ["Vivien", "Marlon", "Kim", "Karl"]
/// let shortNames = cast.filter { $0.count < 5 }
///
/// shortNames.isSubset(of: cast)
/// // true
/// shortNames.contains("Vivien")
/// // false
///
/// - Parameter isIncluded: A closure that takes an element as its argument
/// and returns a Boolean value indicating whether the element should be
/// included in the returned set.
/// - Returns: A set of the elements that `isIncluded` allows.
@inlinable
@available(swift, introduced: 4.0)
public func filter(
_ isIncluded: (Element) throws -> Bool
) rethrows -> Set {
var result = Set()
for element in self {
if try isIncluded(element) {
result.insert(element)
}
}
return result
}
}
extension Set: Collection {
/// The starting position for iterating members of the set.
///
/// If the set is empty, `startIndex` is equal to `endIndex`.
@inlinable // FIXME(sil-serialize-all)
public var startIndex: Index {
return _variantBuffer.startIndex
}
/// The "past the end" position for the set---that is, the position one
/// greater than the last valid subscript argument.
///
/// If the set is empty, `endIndex` is equal to `startIndex`.
@inlinable // FIXME(sil-serialize-all)
public var endIndex: Index {
return _variantBuffer.endIndex
}
/// Accesses the member at the given position.
@inlinable // FIXME(sil-serialize-all)
public subscript(position: Index) -> Element {
return _variantBuffer.assertingGet(at: position)
}
@inlinable // FIXME(sil-serialize-all)
public func index(after i: Index) -> Index {
return _variantBuffer.index(after: i)
}
// APINAMING: complexity docs are broadly missing in this file.
/// Returns the index of the given element in the set, or `nil` if the
/// element is not a member of the set.
///
/// - Parameter member: An element to search for in the set.
/// - Returns: The index of `member` if it exists in the set; otherwise,
/// `nil`.
///
/// - Complexity: O(1)
@inlinable // FIXME(sil-serialize-all)
public func firstIndex(of member: Element) -> Index? {
return _variantBuffer.index(forKey: member)
}
@inlinable // FIXME(sil-serialize-all)
public func _customIndexOfEquatableElement(
_ member: Element
) -> Index?? {
return Optional(firstIndex(of: member))
}
@inlinable // FIXME(sil-serialize-all)
public func _customLastIndexOfEquatableElement(
_ member: Element
) -> Index?? {
// The first and last elements are the same because each element is unique.
return _customIndexOfEquatableElement(member)
}
/// The number of elements in the set.
///
/// - Complexity: O(1).
@inlinable // FIXME(sil-serialize-all)
public var count: Int {
return _variantBuffer.count
}
/// A Boolean value that indicates whether the set is empty.
@inlinable // FIXME(sil-serialize-all)
public var isEmpty: Bool {
return count == 0
}
/// The first element of the set.
///
/// The first element of the set is not necessarily the first element added
/// to the set. Don't expect any particular ordering of set elements.
///
/// If the set is empty, the value of this property is `nil`.
@inlinable // FIXME(sil-serialize-all)
public var first: Element? {
return count > 0 ? self[startIndex] : nil
}
}
/// Check for both subset and equality relationship between
/// a set and some sequence (which may itself be a `Set`).
///
/// (isSubset: lhs ⊂ rhs, isEqual: lhs ⊂ rhs and |lhs| = |rhs|)
@inlinable
internal func _compareSets<Element>(_ lhs: Set<Element>, _ rhs: Set<Element>)
-> (isSubset: Bool, isEqual: Bool) {
// FIXME(performance): performance could be better if we start by comparing
// counts.
for member in lhs {
if !rhs.contains(member) {
return (false, false)
}
}
return (true, lhs.count == rhs.count)
}
// FIXME: rdar://problem/23549059 (Optimize == for Set)
// Look into initially trying to compare the two sets by directly comparing the
// contents of both buffers in order. If they happen to have the exact same
// ordering we can get the `true` response without ever hashing. If the two
// buffers' contents differ at all then we have to fall back to hashing the
// rest of the elements (but we don't need to hash any prefix that did match).
extension Set: Equatable {
/// Returns a Boolean value indicating whether two sets have equal elements.
///
/// - Parameters:
/// - lhs: A set.
/// - rhs: Another set.
/// - Returns: `true` if the `lhs` and `rhs` have the same elements; otherwise,
/// `false`.
@inlinable // FIXME(sil-serialize-all)
public static func == (lhs: Set<Element>, rhs: Set<Element>) -> Bool {
switch (lhs._variantBuffer, rhs._variantBuffer) {
case (.native(let lhsNative), .native(let rhsNative)):
if lhsNative._storage === rhsNative._storage {
return true
}
if lhsNative.count != rhsNative.count {
return false
}
for member in lhs {
let (_, found) =
rhsNative._find(member, startBucket: rhsNative._bucket(member))
if !found {
return false
}
}
return true
#if _runtime(_ObjC)
case (_VariantSetBuffer.cocoa(let lhsCocoa),
_VariantSetBuffer.cocoa(let rhsCocoa)):
return _stdlib_NSObject_isEqual(lhsCocoa.cocoaSet, rhsCocoa.cocoaSet)
case (_VariantSetBuffer.native(let lhsNative),
_VariantSetBuffer.cocoa(let rhsCocoa)):
if lhsNative.count != rhsCocoa.count {
return false
}
let endIndex = lhsNative.endIndex
var i = lhsNative.startIndex
while i != endIndex {
let key = lhsNative.assertingGet(at: i)
let bridgedKey: AnyObject = _bridgeAnythingToObjectiveC(key)
let optRhsValue: AnyObject? = rhsCocoa.maybeGet(bridgedKey)
if let rhsValue = optRhsValue {
if key == _forceBridgeFromObjectiveC(rhsValue, Element.self) {
i = lhsNative.index(after: i)
continue
}
}
i = lhsNative.index(after: i)
return false
}
return true
case (_VariantSetBuffer.cocoa, _VariantSetBuffer.native):
return rhs == lhs
#endif
}
}
}
extension Set: Hashable {
/// Hashes the essential components of this value by feeding them into the
/// given hasher.
///
/// - Parameter hasher: The hasher to use when combining the components
/// of this instance.
@inlinable
public func hash(into hasher: inout Hasher) {
// FIXME(ABI)#177: <rdar://problem/18915294> Cache Set<T> hashValue
var hash = 0
let seed = hasher._generateSeed()
for member in self {
hash ^= member._rawHashValue(seed: seed)
}
hasher.combine(hash)
}
}
extension Set: _HasCustomAnyHashableRepresentation {
public func _toCustomAnyHashable() -> AnyHashable? {
return AnyHashable(_box: _SetAnyHashableBox(self))
}
}
internal struct _SetAnyHashableBox<Element: Hashable>: _AnyHashableBox {
internal let _value: Set<Element>
internal let _canonical: Set<AnyHashable>
internal init(_ value: Set<Element>) {
self._value = value
self._canonical = value as Set<AnyHashable>
}
internal var _base: Any {
return _value
}
internal var _canonicalBox: _AnyHashableBox {
return _SetAnyHashableBox<AnyHashable>(_canonical)
}
internal func _isEqual(to other: _AnyHashableBox) -> Bool? {
guard let other = other as? _SetAnyHashableBox<AnyHashable> else {
return nil
}
return _canonical == other._value
}
internal var _hashValue: Int {
return _canonical.hashValue
}
internal func _hash(into hasher: inout Hasher) {
_canonical.hash(into: &hasher)
}
func _rawHashValue(_seed: (UInt64, UInt64)) -> Int {
return _canonical._rawHashValue(seed: _seed)
}
internal func _unbox<T: Hashable>() -> T? {
return _value as? T
}
internal func _downCastConditional<T>(
into result: UnsafeMutablePointer<T>
) -> Bool {
guard let value = _value as? T else { return false }
result.initialize(to: value)
return true
}
}
extension Set: SetAlgebra {
/// Inserts the given element in the set if it is not already present.
///
/// If an element equal to `newMember` is already contained in the set, this
/// method has no effect. In the following example, a new element is
/// inserted into `classDays`, a set of days of the week. When an existing
/// element is inserted, the `classDays` set does not change.
///
/// enum DayOfTheWeek: Int {
/// case sunday, monday, tuesday, wednesday, thursday,
/// friday, saturday
/// }
///
/// var classDays: Set<DayOfTheWeek> = [.wednesday, .friday]
/// print(classDays.insert(.monday))
/// // Prints "(true, .monday)"
/// print(classDays)
/// // Prints "[.friday, .wednesday, .monday]"
///
/// print(classDays.insert(.friday))
/// // Prints "(false, .friday)"
/// print(classDays)
/// // Prints "[.friday, .wednesday, .monday]"
///
/// - Parameter newMember: An element to insert into the set.
/// - Returns: `(true, newMember)` if `newMember` was not contained in the
/// set. If an element equal to `newMember` was already contained in the
/// set, the method returns `(false, oldMember)`, where `oldMember` is the
/// element that was equal to `newMember`. In some cases, `oldMember` may
/// be distinguishable from `newMember` by identity comparison or some
/// other means.
@inlinable // FIXME(sil-serialize-all)
@discardableResult
public mutating func insert(
_ newMember: Element
) -> (inserted: Bool, memberAfterInsert: Element) {
return _variantBuffer.insert(newMember)
}
/// Inserts the given element into the set unconditionally.
///
/// If an element equal to `newMember` is already contained in the set,
/// `newMember` replaces the existing element. In this example, an existing
/// element is inserted into `classDays`, a set of days of the week.
///
/// enum DayOfTheWeek: Int {
/// case sunday, monday, tuesday, wednesday, thursday,
/// friday, saturday
/// }
///
/// var classDays: Set<DayOfTheWeek> = [.monday, .wednesday, .friday]
/// print(classDays.update(with: .monday))
/// // Prints "Optional(.monday)"
///
/// - Parameter newMember: An element to insert into the set.
/// - Returns: An element equal to `newMember` if the set already contained
/// such a member; otherwise, `nil`. In some cases, the returned element
/// may be distinguishable from `newMember` by identity comparison or some
/// other means.
@inlinable // FIXME(sil-serialize-all)
@discardableResult
public mutating func update(with newMember: Element) -> Element? {
return _variantBuffer.update(with: newMember)
}
/// Removes the specified element from the set.
///
/// This example removes the element `"sugar"` from a set of ingredients.
///
/// var ingredients: Set = ["cocoa beans", "sugar", "cocoa butter", "salt"]
/// let toRemove = "sugar"
/// if let removed = ingredients.remove(toRemove) {
/// print("The recipe is now \(removed)-free.")
/// }
/// // Prints "The recipe is now sugar-free."
///
/// - Parameter member: The element to remove from the set.
/// - Returns: The value of the `member` parameter if it was a member of the
/// set; otherwise, `nil`.
@inlinable // FIXME(sil-serialize-all)
@discardableResult
public mutating func remove(_ member: Element) -> Element? {
return _variantBuffer.remove(member)
}
/// Removes the element at the given index of the set.
///
/// - Parameter position: The index of the member to remove. `position` must
/// be a valid index of the set, and must not be equal to the set's end
/// index.
/// - Returns: The element that was removed from the set.
@inlinable // FIXME(sil-serialize-all)
@discardableResult
public mutating func remove(at position: Index) -> Element {
return _variantBuffer.remove(at: position)
}
/// Removes all members from the set.
///
/// - Parameter keepingCapacity: If `true`, the set's buffer capacity is
/// preserved; if `false`, the underlying buffer is released. The
/// default is `false`.
@inlinable // FIXME(sil-serialize-all)
public mutating func removeAll(keepingCapacity keepCapacity: Bool = false) {
_variantBuffer.removeAll(keepingCapacity: keepCapacity)
}
/// Removes the first element of the set.
///
/// Because a set is not an ordered collection, the "first" element may not
/// be the first element that was added to the set. The set must not be
/// empty.
///
/// - Complexity: Amortized O(1) if the set does not wrap a bridged `NSSet`.
/// If the set wraps a bridged `NSSet`, the performance is unspecified.
///
/// - Returns: A member of the set.
@inlinable // FIXME(sil-serialize-all)
@discardableResult
public mutating func removeFirst() -> Element {
_precondition(!isEmpty, "Can't removeFirst from an empty Set")
return remove(at: startIndex)
}
//
// APIs below this comment should be implemented strictly in terms of
// *public* APIs above. `_variantBuffer` should not be accessed directly.
//
// This separates concerns for testing. Tests for the following APIs need
// not to concern themselves with testing correctness of behavior of
// underlying buffer (and different variants of it), only correctness of the
// API itself.
//
/// Creates an empty set.
///
/// This is equivalent to initializing with an empty array literal. For
/// example:
///
/// var emptySet = Set<Int>()
/// print(emptySet.isEmpty)
/// // Prints "true"
///
/// emptySet = []
/// print(emptySet.isEmpty)
/// // Prints "true"
@inlinable // FIXME(sil-serialize-all)
public init() {
self = Set<Element>(_nativeBuffer: _NativeBuffer())
}
/// Creates a new set from a finite sequence of items.
///
/// Use this initializer to create a new set from an existing sequence, for
/// example, an array or a range.
///
/// let validIndices = Set(0..<7).subtracting([2, 4, 5])
/// print(validIndices)
/// // Prints "[6, 0, 1, 3]"
///
/// This initializer can also be used to restore set methods after performing
/// sequence operations such as `filter(_:)` or `map(_:)` on a set. For
/// example, after filtering a set of prime numbers to remove any below 10,
/// you can create a new set by using this initializer.
///
/// let primes: Set = [2, 3, 5, 7, 11, 13, 17, 19, 23]
/// let laterPrimes = Set(primes.lazy.filter { $0 > 10 })
/// print(laterPrimes)
/// // Prints "[17, 19, 23, 11, 13]"
///
/// - Parameter sequence: The elements to use as members of the new set.
@inlinable // FIXME(sil-serialize-all)
public init<Source: Sequence>(_ sequence: Source)
where Source.Element == Element {
self.init(minimumCapacity: sequence.underestimatedCount)
if let s = sequence as? Set<Element> {
// If this sequence is actually a native `Set`, then we can quickly
// adopt its native buffer and let COW handle uniquing only
// if necessary.
switch s._variantBuffer {
case .native(let buffer):
_variantBuffer = .native(buffer)
#if _runtime(_ObjC)
case .cocoa(let owner):
_variantBuffer = .cocoa(owner)
#endif
}
} else {
for item in sequence {
insert(item)
}
}
}
/// Returns a Boolean value that indicates whether the set is a subset of the
/// given sequence.
///
/// Set *A* is a subset of another set *B* if every member of *A* is also a
/// member of *B*.
///
/// let employees = ["Alicia", "Bethany", "Chris", "Diana", "Eric"]
/// let attendees: Set = ["Alicia", "Bethany", "Diana"]
/// print(attendees.isSubset(of: employees))
/// // Prints "true"
///
/// - Parameter possibleSuperset: A sequence of elements. `possibleSuperset`
/// must be finite.
/// - Returns: `true` if the set is a subset of `possibleSuperset`;
/// otherwise, `false`.
@inlinable
public func isSubset<S: Sequence>(of possibleSuperset: S) -> Bool
where S.Element == Element {
// FIXME(performance): isEmpty fast path, here and elsewhere.
let other = Set(possibleSuperset)
return isSubset(of: other)
}
/// Returns a Boolean value that indicates whether the set is a strict subset
/// of the given sequence.
///
/// Set *A* is a strict subset of another set *B* if every member of *A* is
/// also a member of *B* and *B* contains at least one element that is not a
/// member of *A*.
///
/// let employees = ["Alicia", "Bethany", "Chris", "Diana", "Eric"]
/// let attendees: Set = ["Alicia", "Bethany", "Diana"]
/// print(attendees.isStrictSubset(of: employees))
/// // Prints "true"
///
/// // A set is never a strict subset of itself:
/// print(attendees.isStrictSubset(of: attendees))
/// // Prints "false"
///
/// - Parameter possibleStrictSuperset: A sequence of elements.
/// `possibleStrictSuperset` must be finite.
/// - Returns: `true` is the set is strict subset of
/// `possibleStrictSuperset`; otherwise, `false`.
@inlinable
public func isStrictSubset<S: Sequence>(of possibleStrictSuperset: S) -> Bool
where S.Element == Element {
// FIXME: code duplication.
let other = Set(possibleStrictSuperset)
return isStrictSubset(of: other)
}
/// Returns a Boolean value that indicates whether the set is a superset of
/// the given sequence.
///
/// Set *A* is a superset of another set *B* if every member of *B* is also a
/// member of *A*.
///
/// let employees: Set = ["Alicia", "Bethany", "Chris", "Diana", "Eric"]
/// let attendees = ["Alicia", "Bethany", "Diana"]
/// print(employees.isSuperset(of: attendees))
/// // Prints "true"
///
/// - Parameter possibleSubset: A sequence of elements. `possibleSubset` must
/// be finite.
/// - Returns: `true` if the set is a superset of `possibleSubset`;
/// otherwise, `false`.
@inlinable
public func isSuperset<S: Sequence>(of possibleSubset: S) -> Bool
where S.Element == Element {
// FIXME(performance): Don't build a set; just ask if every element is in
// `self`.
let other = Set(possibleSubset)
return other.isSubset(of: self)
}
/// Returns a Boolean value that indicates whether the set is a strict
/// superset of the given sequence.
///
/// Set *A* is a strict superset of another set *B* if every member of *B* is
/// also a member of *A* and *A* contains at least one element that is *not*
/// a member of *B*.
///
/// let employees: Set = ["Alicia", "Bethany", "Chris", "Diana", "Eric"]
/// let attendees = ["Alicia", "Bethany", "Diana"]
/// print(employees.isStrictSuperset(of: attendees))
/// // Prints "true"
/// print(employees.isStrictSuperset(of: employees))
/// // Prints "false"
///
/// - Parameter possibleStrictSubset: A sequence of elements.
/// `possibleStrictSubset` must be finite.
/// - Returns: `true` if the set is a strict superset of
/// `possibleStrictSubset`; otherwise, `false`.
@inlinable // FIXME(sil-serialize-all)
public func isStrictSuperset<S: Sequence>(of possibleStrictSubset: S) -> Bool
where S.Element == Element {
let other = Set(possibleStrictSubset)
return other.isStrictSubset(of: self)
}
/// Returns a Boolean value that indicates whether the set has no members in
/// common with the given sequence.
///
/// In the following example, the `employees` set is disjoint with the
/// elements of the `visitors` array because no name appears in both.
///
/// let employees: Set = ["Alicia", "Bethany", "Chris", "Diana", "Eric"]
/// let visitors = ["Marcia", "Nathaniel", "Olivia"]
/// print(employees.isDisjoint(with: visitors))
/// // Prints "true"
///
/// - Parameter other: A sequence of elements. `other` must be finite.
/// - Returns: `true` if the set has no elements in common with `other`;
/// otherwise, `false`.
@inlinable // FIXME(sil-serialize-all)
public func isDisjoint<S: Sequence>(with other: S) -> Bool
where S.Element == Element {
// FIXME(performance): Don't need to build a set.
let otherSet = Set(other)
return isDisjoint(with: otherSet)
}
/// Returns a new set with the elements of both this set and the given
/// sequence.
///
/// In the following example, the `attendeesAndVisitors` set is made up
/// of the elements of the `attendees` set and the `visitors` array:
///
/// let attendees: Set = ["Alicia", "Bethany", "Diana"]
/// let visitors = ["Marcia", "Nathaniel"]
/// let attendeesAndVisitors = attendees.union(visitors)
/// print(attendeesAndVisitors)
/// // Prints "["Diana", "Nathaniel", "Bethany", "Alicia", "Marcia"]"
///
/// If the set already contains one or more elements that are also in
/// `other`, the existing members are kept. If `other` contains multiple
/// instances of equivalent elements, only the first instance is kept.
///
/// let initialIndices = Set(0..<5)
/// let expandedIndices = initialIndices.union([2, 3, 6, 6, 7, 7])
/// print(expandedIndices)
/// // Prints "[2, 4, 6, 7, 0, 1, 3]"
///
/// - Parameter other: A sequence of elements. `other` must be finite.
/// - Returns: A new set with the unique elements of this set and `other`.
@inlinable
public func union<S: Sequence>(_ other: S) -> Set<Element>
where S.Element == Element {
var newSet = self
newSet.formUnion(other)
return newSet
}
/// Inserts the elements of the given sequence into the set.
///
/// If the set already contains one or more elements that are also in
/// `other`, the existing members are kept. If `other` contains multiple
/// instances of equivalent elements, only the first instance is kept.
///
/// var attendees: Set = ["Alicia", "Bethany", "Diana"]
/// let visitors = ["Diana", "Marcia", "Nathaniel"]
/// attendees.formUnion(visitors)
/// print(attendees)
/// // Prints "["Diana", "Nathaniel", "Bethany", "Alicia", "Marcia"]"
///
/// - Parameter other: A sequence of elements. `other` must be finite.
@inlinable
public mutating func formUnion<S: Sequence>(_ other: S)
where S.Element == Element {
for item in other {
insert(item)
}
}
/// Returns a new set containing the elements of this set that do not occur
/// in the given sequence.
///
/// In the following example, the `nonNeighbors` set is made up of the
/// elements of the `employees` set that are not elements of `neighbors`:
///
/// let employees: Set = ["Alicia", "Bethany", "Chris", "Diana", "Eric"]
/// let neighbors = ["Bethany", "Eric", "Forlani", "Greta"]
/// let nonNeighbors = employees.subtracting(neighbors)
/// print(nonNeighbors)
/// // Prints "["Chris", "Diana", "Alicia"]"
///
/// - Parameter other: A sequence of elements. `other` must be finite.
/// - Returns: A new set.
@inlinable
public func subtracting<S: Sequence>(_ other: S) -> Set<Element>
where S.Element == Element {
return self._subtracting(other)
}
@inlinable // FIXME(sil-serialize-all)
internal func _subtracting<S: Sequence>(_ other: S) -> Set<Element>
where S.Element == Element {
var newSet = self
newSet.subtract(other)
return newSet
}
/// Removes the elements of the given sequence from the set.
///
/// In the following example, the elements of the `employees` set that are
/// also elements of the `neighbors` array are removed. In particular, the
/// names `"Bethany"` and `"Eric"` are removed from `employees`.
///
/// var employees: Set = ["Alicia", "Bethany", "Chris", "Diana", "Eric"]
/// let neighbors = ["Bethany", "Eric", "Forlani", "Greta"]
/// employees.subtract(neighbors)
/// print(employees)
/// // Prints "["Chris", "Diana", "Alicia"]"
///
/// - Parameter other: A sequence of elements. `other` must be finite.
@inlinable // FIXME(sil-serialize-all)
public mutating func subtract<S: Sequence>(_ other: S)
where S.Element == Element {
_subtract(other)
}
@inlinable // FIXME(sil-serialize-all)
internal mutating func _subtract<S: Sequence>(_ other: S)
where S.Element == Element {
for item in other {
remove(item)
}
}
/// Returns a new set with the elements that are common to both this set and
/// the given sequence.
///
/// In the following example, the `bothNeighborsAndEmployees` set is made up
/// of the elements that are in *both* the `employees` and `neighbors` sets.
/// Elements that are in only one or the other are left out of the result of
/// the intersection.
///
/// let employees: Set = ["Alicia", "Bethany", "Chris", "Diana", "Eric"]
/// let neighbors = ["Bethany", "Eric", "Forlani", "Greta"]
/// let bothNeighborsAndEmployees = employees.intersection(neighbors)
/// print(bothNeighborsAndEmployees)
/// // Prints "["Bethany", "Eric"]"
///
/// - Parameter other: A sequence of elements. `other` must be finite.
/// - Returns: A new set.
@inlinable
public func intersection<S: Sequence>(_ other: S) -> Set<Element>
where S.Element == Element {
let otherSet = Set(other)
return intersection(otherSet)
}
/// Removes the elements of the set that aren't also in the given sequence.
///
/// In the following example, the elements of the `employees` set that are
/// not also members of the `neighbors` set are removed. In particular, the
/// names `"Alicia"`, `"Chris"`, and `"Diana"` are removed.
///
/// var employees: Set = ["Alicia", "Bethany", "Chris", "Diana", "Eric"]
/// let neighbors = ["Bethany", "Eric", "Forlani", "Greta"]
/// employees.formIntersection(neighbors)
/// print(employees)
/// // Prints "["Bethany", "Eric"]"
///
/// - Parameter other: A sequence of elements. `other` must be finite.
@inlinable
public mutating func formIntersection<S: Sequence>(_ other: S)
where S.Element == Element {
// Because `intersect` needs to both modify and iterate over
// the left-hand side, the index may become invalidated during
// traversal so an intermediate set must be created.
//
// FIXME(performance): perform this operation at a lower level
// to avoid invalidating the index and avoiding a copy.
let result = self.intersection(other)
// The result can only have fewer or the same number of elements.
// If no elements were removed, don't perform a reassignment
// as this may cause an unnecessary uniquing COW.
if result.count != count {
self = result
}
}
/// Returns a new set with the elements that are either in this set or in the
/// given sequence, but not in both.
///
/// In the following example, the `eitherNeighborsOrEmployees` set is made up
/// of the elements of the `employees` and `neighbors` sets that are not in
/// both `employees` *and* `neighbors`. In particular, the names `"Bethany"`
/// and `"Eric"` do not appear in `eitherNeighborsOrEmployees`.
///
/// let employees: Set = ["Alicia", "Bethany", "Diana", "Eric"]
/// let neighbors = ["Bethany", "Eric", "Forlani"]
/// let eitherNeighborsOrEmployees = employees.symmetricDifference(neighbors)
/// print(eitherNeighborsOrEmployees)
/// // Prints "["Diana", "Forlani", "Alicia"]"
///
/// - Parameter other: A sequence of elements. `other` must be finite.
/// - Returns: A new set.
@inlinable
public func symmetricDifference<S: Sequence>(_ other: S) -> Set<Element>
where S.Element == Element {
var newSet = self
newSet.formSymmetricDifference(other)
return newSet
}
/// Replace this set with the elements contained in this set or the given
/// set, but not both.
///
/// In the following example, the elements of the `employees` set that are
/// also members of `neighbors` are removed from `employees`, while the
/// elements of `neighbors` that are not members of `employees` are added to
/// `employees`. In particular, the names `"Bethany"` and `"Eric"` are
/// removed from `employees` while the name `"Forlani"` is added.
///
/// var employees: Set = ["Alicia", "Bethany", "Diana", "Eric"]
/// let neighbors = ["Bethany", "Eric", "Forlani"]
/// employees.formSymmetricDifference(neighbors)
/// print(employees)
/// // Prints "["Diana", "Forlani", "Alicia"]"
///
/// - Parameter other: A sequence of elements. `other` must be finite.
@inlinable
public mutating func formSymmetricDifference<S: Sequence>(_ other: S)
where S.Element == Element {
let otherSet = Set(other)
formSymmetricDifference(otherSet)
}
}
extension Set: CustomStringConvertible, CustomDebugStringConvertible {
/// A string that represents the contents of the set.
@inlinable // FIXME(sil-serialize-all)
public var description: String {
return _makeCollectionDescription(for: self, withTypeName: nil)
}
/// A string that represents the contents of the set, suitable for debugging.
public var debugDescription: String {
return _makeCollectionDescription(for: self, withTypeName: "Set")
}
}
#if _runtime(_ObjC)
@_silgen_name("swift_stdlib_CFSetGetValues")
@usableFromInline // FIXME(sil-serialize-all)
internal
func _stdlib_CFSetGetValues(_ nss: _NSSet, _: UnsafeMutablePointer<AnyObject>)
/// Equivalent to `NSSet.allObjects`, but does not leave objects on the
/// autorelease pool.
@inlinable // FIXME(sil-serialize-all)
internal func _stdlib_NSSet_allObjects(_ nss: _NSSet) ->
_HeapBuffer<Int, AnyObject> {
let count = nss.count
let storage = _HeapBuffer<Int, AnyObject>(
_HeapBufferStorage<Int, AnyObject>.self, count, count)
_stdlib_CFSetGetValues(nss, storage.baseAddress)
return storage
}
#endif
//===--- Compiler conversion/casting entry points for Set<Element> --------===//
/// Perform a non-bridged upcast that always succeeds.
///
/// - Precondition: `BaseValue` is a base class or base `@objc`
/// protocol (such as `AnyObject`) of `DerivedValue`.
@inlinable // FIXME(sil-serialize-all)
public func _setUpCast<DerivedValue, BaseValue>(_ source: Set<DerivedValue>)
-> Set<BaseValue> {
var builder = _SetBuilder<BaseValue>(count: source.count)
for x in source {
builder.add(member: x as! BaseValue)
}
return builder.take()
}
#if _runtime(_ObjC)
/// Implements an unconditional upcast that involves bridging.
///
/// The cast can fail if bridging fails.
///
/// - Precondition: `SwiftValue` is bridged to Objective-C
/// and requires non-trivial bridging.
@inlinable // FIXME(sil-serialize-all)
public func _setBridgeToObjectiveC<SwiftValue, ObjCValue>(
_ source: Set<SwiftValue>
) -> Set<ObjCValue> {
_sanityCheck(_isClassOrObjCExistential(ObjCValue.self))
_sanityCheck(!_isBridgedVerbatimToObjectiveC(SwiftValue.self))
var result = Set<ObjCValue>(minimumCapacity: source.count)
let valueBridgesDirectly =
_isBridgedVerbatimToObjectiveC(SwiftValue.self) ==
_isBridgedVerbatimToObjectiveC(ObjCValue.self)
for member in source {
var bridgedMember: ObjCValue
if valueBridgesDirectly {
bridgedMember = unsafeBitCast(member, to: ObjCValue.self)
} else {
let bridged: AnyObject = _bridgeAnythingToObjectiveC(member)
bridgedMember = unsafeBitCast(bridged, to: ObjCValue.self)
}
result.insert(bridgedMember)
}
return result
}
#endif
/// Called by the casting machinery.
@_silgen_name("_swift_setDownCastIndirect")
internal func _setDownCastIndirect<SourceValue, TargetValue>(
_ source: UnsafePointer<Set<SourceValue>>,
_ target: UnsafeMutablePointer<Set<TargetValue>>) {
target.initialize(to: _setDownCast(source.pointee))
}
/// Implements a forced downcast. This operation should have O(1) complexity.
///
/// The cast can fail if bridging fails. The actual checks and bridging can be
/// deferred.
///
/// - Precondition: `DerivedValue` is a subtype of `BaseValue` and both
/// are reference types.
@inlinable // FIXME(sil-serialize-all)
public func _setDownCast<BaseValue, DerivedValue>(_ source: Set<BaseValue>)
-> Set<DerivedValue> {
#if _runtime(_ObjC)
if _isClassOrObjCExistential(BaseValue.self)
&& _isClassOrObjCExistential(DerivedValue.self) {
switch source._variantBuffer {
case _VariantSetBuffer.native(let buffer):
return Set(_immutableCocoaSet: buffer.bridged())
case _VariantSetBuffer.cocoa(let cocoaBuffer):
return Set(_immutableCocoaSet: cocoaBuffer.cocoaSet)
}
}
#endif
return _setDownCastConditional(source)!
}
/// Called by the casting machinery.
@_silgen_name("_swift_setDownCastConditionalIndirect")
internal func _setDownCastConditionalIndirect<SourceValue, TargetValue>(
_ source: UnsafePointer<Set<SourceValue>>,
_ target: UnsafeMutablePointer<Set<TargetValue>>
) -> Bool {
if let result: Set<TargetValue> = _setDownCastConditional(source.pointee) {
target.initialize(to: result)
return true
}
return false
}
/// Implements a conditional downcast.
///
/// If the cast fails, the function returns `nil`. All checks should be
/// performed eagerly.
///
/// - Precondition: `DerivedValue` is a subtype of `BaseValue` and both
/// are reference types.
@inlinable // FIXME(sil-serialize-all)
public func _setDownCastConditional<BaseValue, DerivedValue>(
_ source: Set<BaseValue>
) -> Set<DerivedValue>? {
var result = Set<DerivedValue>(minimumCapacity: source.count)
for member in source {
if let derivedMember = member as? DerivedValue {
result.insert(derivedMember)
continue
}
return nil
}
return result
}
#if _runtime(_ObjC)
/// Implements an unconditional downcast that involves bridging.
///
/// - Precondition: At least one of `SwiftValue` is a bridged value
/// type, and the corresponding `ObjCValue` is a reference type.
@inlinable // FIXME(sil-serialize-all)
public func _setBridgeFromObjectiveC<ObjCValue, SwiftValue>(
_ source: Set<ObjCValue>
) -> Set<SwiftValue> {
let result: Set<SwiftValue>? = _setBridgeFromObjectiveCConditional(source)
_precondition(result != nil, "This set cannot be bridged from Objective-C")
return result!
}
/// Implements a conditional downcast that involves bridging.
///
/// If the cast fails, the function returns `nil`. All checks should be
/// performed eagerly.
///
/// - Precondition: At least one of `SwiftValue` is a bridged value
/// type, and the corresponding `ObjCValue` is a reference type.
@inlinable // FIXME(sil-serialize-all)
public func _setBridgeFromObjectiveCConditional<
ObjCValue, SwiftValue
>(
_ source: Set<ObjCValue>
) -> Set<SwiftValue>? {
_sanityCheck(_isClassOrObjCExistential(ObjCValue.self))
_sanityCheck(!_isBridgedVerbatimToObjectiveC(SwiftValue.self))
let valueBridgesDirectly =
_isBridgedVerbatimToObjectiveC(SwiftValue.self) ==
_isBridgedVerbatimToObjectiveC(ObjCValue.self)
var result = Set<SwiftValue>(minimumCapacity: source.count)
for value in source {
// Downcast the value.
var resultValue: SwiftValue
if valueBridgesDirectly {
if let bridgedValue = value as? SwiftValue {
resultValue = bridgedValue
} else {
return nil
}
} else {
if let bridgedValue = _conditionallyBridgeFromObjectiveC(
_reinterpretCastToAnyObject(value), SwiftValue.self) {
resultValue = bridgedValue
} else {
return nil
}
}
result.insert(resultValue)
}
return result
}
#endif
extension Set {
/// Removes the elements of the given set from this set.
///
/// In the following example, the elements of the `employees` set that are
/// also members of the `neighbors` set are removed. In particular, the
/// names `"Bethany"` and `"Eric"` are removed from `employees`.
///
/// var employees: Set = ["Alicia", "Bethany", "Chris", "Diana", "Eric"]
/// let neighbors: Set = ["Bethany", "Eric", "Forlani", "Greta"]
/// employees.subtract(neighbors)
/// print(employees)
/// // Prints "["Diana", "Chris", "Alicia"]"
///
/// - Parameter other: Another set.
@inlinable // FIXME(sil-serialize-all)
public mutating func subtract(_ other: Set<Element>) {
_subtract(other)
}
/// Returns a Boolean value that indicates whether this set is a subset of
/// the given set.
///
/// Set *A* is a subset of another set *B* if every member of *A* is also a
/// member of *B*.
///
/// let employees: Set = ["Alicia", "Bethany", "Chris", "Diana", "Eric"]
/// let attendees: Set = ["Alicia", "Bethany", "Diana"]
/// print(attendees.isSubset(of: employees))
/// // Prints "true"
///
/// - Parameter other: Another set.
/// - Returns: `true` if the set is a subset of `other`; otherwise, `false`.
@inlinable
public func isSubset(of other: Set<Element>) -> Bool {
let (isSubset, isEqual) = _compareSets(self, other)
return isSubset || isEqual
}
/// Returns a Boolean value that indicates whether this set is a superset of
/// the given set.
///
/// Set *A* is a superset of another set *B* if every member of *B* is also a
/// member of *A*.
///
/// let employees: Set = ["Alicia", "Bethany", "Chris", "Diana", "Eric"]
/// let attendees: Set = ["Alicia", "Bethany", "Diana"]
/// print(employees.isSuperset(of: attendees))
/// // Prints "true"
///
/// - Parameter other: Another set.
/// - Returns: `true` if the set is a superset of `other`; otherwise,
/// `false`.
@inlinable
public func isSuperset(of other: Set<Element>) -> Bool {
return other.isSubset(of: self)
}
/// Returns a Boolean value that indicates whether this set has no members in
/// common with the given set.
///
/// In the following example, the `employees` set is disjoint with the
/// `visitors` set because no name appears in both sets.
///
/// let employees: Set = ["Alicia", "Bethany", "Chris", "Diana", "Eric"]
/// let visitors: Set = ["Marcia", "Nathaniel", "Olivia"]
/// print(employees.isDisjoint(with: visitors))
/// // Prints "true"
///
/// - Parameter other: Another set.
/// - Returns: `true` if the set has no elements in common with `other`;
/// otherwise, `false`.
@inlinable
public func isDisjoint(with other: Set<Element>) -> Bool {
for member in self {
if other.contains(member) {
return false
}
}
return true
}
/// Returns a new set containing the elements of this set that do not occur
/// in the given set.
///
/// In the following example, the `nonNeighbors` set is made up of the
/// elements of the `employees` set that are not elements of `neighbors`:
///
/// let employees: Set = ["Alicia", "Bethany", "Chris", "Diana", "Eric"]
/// let neighbors: Set = ["Bethany", "Eric", "Forlani", "Greta"]
/// let nonNeighbors = employees.subtracting(neighbors)
/// print(nonNeighbors)
/// // Prints "["Diana", "Chris", "Alicia"]"
///
/// - Parameter other: Another set.
/// - Returns: A new set.
@inlinable
public func subtracting(_ other: Set<Element>) -> Set<Element> {
return self._subtracting(other)
}
/// Returns a Boolean value that indicates whether the set is a strict
/// superset of the given sequence.
///
/// Set *A* is a strict superset of another set *B* if every member of *B* is
/// also a member of *A* and *A* contains at least one element that is *not*
/// a member of *B*.
///
/// let employees: Set = ["Alicia", "Bethany", "Chris", "Diana", "Eric"]
/// let attendees: Set = ["Alicia", "Bethany", "Diana"]
/// print(employees.isStrictSuperset(of: attendees))
/// // Prints "true"
/// print(employees.isStrictSuperset(of: employees))
/// // Prints "false"
///
/// - Parameter other: Another set.
/// - Returns: `true` if the set is a strict superset of
/// `other`; otherwise, `false`.
@inlinable
public func isStrictSuperset(of other: Set<Element>) -> Bool {
return self.isSuperset(of: other) && self != other
}
/// Returns a Boolean value that indicates whether the set is a strict subset
/// of the given sequence.
///
/// Set *A* is a strict subset of another set *B* if every member of *A* is
/// also a member of *B* and *B* contains at least one element that is not a
/// member of *A*.
///
/// let employees: Set = ["Alicia", "Bethany", "Chris", "Diana", "Eric"]
/// let attendees: Set = ["Alicia", "Bethany", "Diana"]
/// print(attendees.isStrictSubset(of: employees))
/// // Prints "true"
///
/// // A set is never a strict subset of itself:
/// print(attendees.isStrictSubset(of: attendees))
/// // Prints "false"
///
/// - Parameter other: Another set.
/// - Returns: `true` if the set is a strict subset of
/// `other`; otherwise, `false`.
@inlinable
public func isStrictSubset(of other: Set<Element>) -> Bool {
return other.isStrictSuperset(of: self)
}
/// Returns a new set with the elements that are common to both this set and
/// the given sequence.
///
/// In the following example, the `bothNeighborsAndEmployees` set is made up
/// of the elements that are in *both* the `employees` and `neighbors` sets.
/// Elements that are in only one or the other are left out of the result of
/// the intersection.
///
/// let employees: Set = ["Alicia", "Bethany", "Chris", "Diana", "Eric"]
/// let neighbors: Set = ["Bethany", "Eric", "Forlani", "Greta"]
/// let bothNeighborsAndEmployees = employees.intersection(neighbors)
/// print(bothNeighborsAndEmployees)
/// // Prints "["Bethany", "Eric"]"
///
/// - Parameter other: Another set.
/// - Returns: A new set.
@inlinable
public func intersection(_ other: Set<Element>) -> Set<Element> {
var newSet = Set<Element>()
for member in self {
if other.contains(member) {
newSet.insert(member)
}
}
return newSet
}
/// Removes the elements of the set that are also in the given sequence and
/// adds the members of the sequence that are not already in the set.
///
/// In the following example, the elements of the `employees` set that are
/// also members of `neighbors` are removed from `employees`, while the
/// elements of `neighbors` that are not members of `employees` are added to
/// `employees`. In particular, the names `"Alicia"`, `"Chris"`, and
/// `"Diana"` are removed from `employees` while the names `"Forlani"` and
/// `"Greta"` are added.
///
/// var employees: Set = ["Alicia", "Bethany", "Chris", "Diana", "Eric"]
/// let neighbors: Set = ["Bethany", "Eric", "Forlani", "Greta"]
/// employees.formSymmetricDifference(neighbors)
/// print(employees)
/// // Prints "["Diana", "Chris", "Forlani", "Alicia", "Greta"]"
///
/// - Parameter other: Another set.
@inlinable
public mutating func formSymmetricDifference(_ other: Set<Element>) {
for member in other {
if contains(member) {
remove(member)
} else {
insert(member)
}
}
}
}
//===--- APIs templated for Dictionary and Set ----------------------------===//
/// This protocol is only used for compile-time checks that
/// every buffer type implements all required operations.
internal protocol _SetBuffer { // FIXME: Remove or refactor for Set.
associatedtype Element
associatedtype Index
var startIndex: Index { get }
var endIndex: Index { get }
func index(after i: Index) -> Index
func formIndex(after i: inout Index)
func index(forKey key: Element) -> Index?
var count: Int { get }
func assertingGet(at i: Index) -> Element
func maybeGet(_ key: Element) -> Element?
}
/// An instance of this class has all `Set` data tail-allocated.
/// Enough bytes are allocated to hold the bitmap for marking valid entries,
/// keys, and values. The data layout starts with the bitmap, followed by the
/// keys, followed by the values.
//
// See the docs at the top of the file for more details on this type
//
// NOTE: The precise layout of this type is relied on in the runtime
// to provide a statically allocated empty singleton.
// See stdlib/public/stubs/GlobalObjects.cpp for details.
@_fixed_layout // FIXME(sil-serialize-all)
@usableFromInline // FIXME(sil-serialize-all)
@_objc_non_lazy_realization
internal class _RawNativeSetStorage: _SwiftNativeNSSet, _NSSetCore {
@usableFromInline // FIXME(sil-serialize-all)
@nonobjc
internal final var bucketCount: Int
@usableFromInline // FIXME(sil-serialize-all)
internal final var count: Int
@usableFromInline // FIXME(sil-serialize-all)
internal final var initializedEntries: _UnsafeBitMap
@usableFromInline // FIXME(sil-serialize-all)
@nonobjc
internal final var keys: UnsafeMutableRawPointer
@usableFromInline // FIXME(sil-serialize-all)
internal final var seed: (UInt64, UInt64)
// This API is unsafe and needs a `_fixLifetime` in the caller.
@inlinable // FIXME(sil-serialize-all)
@nonobjc
internal final
var _initializedHashtableEntriesBitMapBuffer: UnsafeMutablePointer<UInt> {
return UnsafeMutablePointer(Builtin.projectTailElems(self, UInt.self))
}
/// The empty singleton that is used for every single Dictionary that is
/// created without any elements. The contents of the storage should never
/// be mutated.
@inlinable // FIXME(sil-serialize-all)
@nonobjc
internal static var empty: _RawNativeSetStorage {
return Builtin.bridgeFromRawPointer(
Builtin.addressof(&_swiftEmptySetStorage))
}
// This type is made with allocWithTailElems, so no init is ever called.
// But we still need to have an init to satisfy the compiler.
@inlinable // FIXME(sil-serialize-all)
@nonobjc
internal init(_doNotCallMe: ()) {
_sanityCheckFailure("Only create this by using the `empty` singleton")
}
#if _runtime(_ObjC)
//
// NSSet implementation, assuming Self is the empty singleton
//
/// Get the NSEnumerator implementation for self.
/// _HashableTypedNativeSetStorage overloads this to give
/// _NativeSelfNSEnumerator proper type parameters.
@objc
internal func enumerator() -> _NSEnumerator {
return _NativeSetNSEnumerator<AnyObject>(
_NativeSetBuffer(_storage: self))
}
@inlinable // FIXME(sil-serialize-all)
@objc(copyWithZone:)
internal func copy(with zone: _SwiftNSZone?) -> AnyObject {
return self
}
@inlinable // FIXME(sil-serialize-all)
@objc(countByEnumeratingWithState:objects:count:)
internal func countByEnumerating(
with state: UnsafeMutablePointer<_SwiftNSFastEnumerationState>,
objects: UnsafeMutablePointer<AnyObject>?, count: Int
) -> Int {
// Even though we never do anything in here, we need to update the
// state so that callers know we actually ran.
var theState = state.pointee
if theState.state == 0 {
theState.state = 1 // Arbitrary non-zero value.
theState.itemsPtr = AutoreleasingUnsafeMutablePointer(objects)
theState.mutationsPtr = _fastEnumerationStorageMutationsPtr
}
state.pointee = theState
return 0
}
@inlinable // FIXME(sil-serialize-all)
@objc
internal required init(objects: UnsafePointer<AnyObject?>, count: Int) {
_sanityCheckFailure("don't call this designated initializer")
}
@inlinable // FIXME(sil-serialize-all)
@objc
internal func member(_ object: AnyObject) -> AnyObject? {
return nil
}
@objc
internal func objectEnumerator() -> _NSEnumerator {
return enumerator()
}
#endif
}
// See the docs at the top of this file for a description of this type
@_fixed_layout // FIXME(sil-serialize-all)
@usableFromInline
internal class _TypedNativeSetStorage<Element>: _RawNativeSetStorage {
deinit {
let keys = self.keys.assumingMemoryBound(to: Element.self)
if !_isPOD(Element.self) {
for i in 0 ..< bucketCount {
if initializedEntries[i] {
(keys+i).deinitialize(count: 1)
}
}
}
_fixLifetime(self)
}
// This type is made with allocWithTailElems, so no init is ever called.
// But we still need to have an init to satisfy the compiler.
@inlinable // FIXME(sil-serialize-all)
@nonobjc
override internal init(_doNotCallMe: ()) {
_sanityCheckFailure("Only create this by calling Buffer's inits")
}
#if _runtime(_ObjC)
@inlinable // FIXME(sil-serialize-all)
@objc
internal required init(objects: UnsafePointer<AnyObject?>, count: Int) {
_sanityCheckFailure("don't call this designated initializer")
}
#endif
}
// See the docs at the top of this file for a description of this type
@_fixed_layout // FIXME(sil-serialize-all)
@usableFromInline
final internal class _HashableTypedNativeSetStorage<Element: Hashable>
: _TypedNativeSetStorage<Element> {
@usableFromInline
internal typealias FullContainer = Set<Element>
@usableFromInline
internal typealias Buffer = _NativeSetBuffer<Element>
// This type is made with allocWithTailElems, so no init is ever called.
// But we still need to have an init to satisfy the compiler.
@inlinable // FIXME(sil-serialize-all)
@nonobjc
override internal init(_doNotCallMe: ()) {
_sanityCheckFailure("Only create this by calling Buffer's inits'")
}
#if _runtime(_ObjC)
// NSSet bridging:
// All actual functionality comes from buffer/full, which are
// just wrappers around a RawNativeSetStorage.
@inlinable // FIXME(sil-serialize-all)
internal var buffer: Buffer {
return Buffer(_storage: self)
}
@inlinable // FIXME(sil-serialize-all)
internal var full: FullContainer {
return FullContainer(_nativeBuffer: buffer)
}
@objc
internal override func enumerator() -> _NSEnumerator {
return _NativeSetNSEnumerator<Element>(
Buffer(_storage: self))
}
@inlinable // FIXME(sil-serialize-all)
@objc(countByEnumeratingWithState:objects:count:)
internal override func countByEnumerating(
with state: UnsafeMutablePointer<_SwiftNSFastEnumerationState>,
objects: UnsafeMutablePointer<AnyObject>?, count: Int
) -> Int {
var theState = state.pointee
if theState.state == 0 {
theState.state = 1 // Arbitrary non-zero value.
theState.itemsPtr = AutoreleasingUnsafeMutablePointer(objects)
theState.mutationsPtr = _fastEnumerationStorageMutationsPtr
theState.extra.0 = CUnsignedLong(full.startIndex._nativeIndex.offset)
}
// Test 'objects' rather than 'count' because (a) this is very rare anyway,
// and (b) the optimizer should then be able to optimize away the
// unwrapping check below.
if _slowPath(objects == nil) {
return 0
}
let unmanagedObjects = _UnmanagedAnyObjectArray(objects!)
var currIndex = _NativeSetIndex<Element>(
offset: Int(theState.extra.0))
let endIndex = buffer.endIndex
var stored = 0
for i in 0..<count {
if (currIndex == endIndex) {
break
}
unmanagedObjects[i] = buffer.bridgedKey(at: currIndex)
stored += 1
buffer.formIndex(after: &currIndex)
}
theState.extra.0 = CUnsignedLong(currIndex.offset)
state.pointee = theState
return stored
}
@inlinable // FIXME(sil-serialize-all)
@nonobjc
internal func getObjectFor(_ aKey: AnyObject) -> AnyObject? {
guard let nativeKey = _conditionallyBridgeFromObjectiveC(aKey, Element.self)
else { return nil }
let (i, found) = buffer._find(nativeKey,
startBucket: buffer._bucket(nativeKey))
if found {
return buffer.bridgedValue(at: i)
}
return nil
}
@inlinable // FIXME(sil-serialize-all)
@objc
internal required init(objects: UnsafePointer<AnyObject?>, count: Int) {
_sanityCheckFailure("don't call this designated initializer")
}
@inlinable // FIXME(sil-serialize-all)
@objc
override internal func member(_ object: AnyObject) -> AnyObject? {
return getObjectFor(object)
}
#endif
}
/// A wrapper around _RawNativeSetStorage that provides most of the
/// implementation of Set.
///
/// This type and most of its functionality doesn't require Hashable at all.
/// The reason for this is to support storing AnyObject for bridging
/// with _SwiftDeferredNSSet. What functionality actually relies on
/// Hashable can be found in an extension.
@usableFromInline
@_fixed_layout
internal struct _NativeSetBuffer<Element> {
@usableFromInline
internal typealias TypedStorage = _TypedNativeSetStorage<Element>
@usableFromInline
internal typealias Buffer = _NativeSetBuffer<Element>
@usableFromInline
internal typealias Index = _NativeSetIndex<Element>
/// See this comments on _RawNativeSetStorage and its subclasses to
/// understand why we store an untyped storage here.
@usableFromInline // FIXME(sil-serialize-all)
internal var _storage: _RawNativeSetStorage
/// Creates a Buffer with a storage that is typed, but doesn't understand
/// Hashing. Mostly for bridging; prefer `init(minimumCapacity:)`.
@inlinable // FIXME(sil-serialize-all)
internal init(_exactBucketCount bucketCount: Int, unhashable: ()) {
let bitmapWordCount = _UnsafeBitMap.sizeInWords(forSizeInBits: bucketCount)
let storage = Builtin.allocWithTailElems_2(TypedStorage.self,
bitmapWordCount._builtinWordValue, UInt.self,
bucketCount._builtinWordValue, Element.self)
self.init(_exactBucketCount: bucketCount, storage: storage)
}
/// Given a bucket count and uninitialized _RawNativeSetStorage, completes the
/// initialization and returns a Buffer.
@inlinable // FIXME(sil-serialize-all)
internal init(
_exactBucketCount bucketCount: Int,
storage: _RawNativeSetStorage
) {
storage.bucketCount = bucketCount
storage.count = 0
self.init(_storage: storage)
let initializedEntries = _UnsafeBitMap(
storage: _initializedHashtableEntriesBitMapBuffer,
bitCount: bucketCount)
initializedEntries.initializeToZero()
// Compute all the array offsets now, so we don't have to later
let bitmapAddr = Builtin.projectTailElems(_storage, UInt.self)
let bitmapWordCount = _UnsafeBitMap.sizeInWords(forSizeInBits: bucketCount)
let keysAddr = Builtin.getTailAddr_Word(bitmapAddr,
bitmapWordCount._builtinWordValue, UInt.self, Element.self)
// Initialize header
_storage.initializedEntries = initializedEntries
_storage.keys = UnsafeMutableRawPointer(keysAddr)
// We assign a unique hash seed to each distinct hash table size, so that we
// avoid certain copy operations becoming quadratic, without breaking value
// semantics. (See https://bugs.swift.org/browse/SR-3268)
//
// We don't need to generate a brand new seed for each table size: it's
// enough to change a single bit in the global seed by XORing the bucket
// count to it. (The bucket count is always a power of two.)
//
// FIXME: Use an approximation of true per-instance seeding. We can't just
// use the base address, because COW copies need to share the same seed.
let seed = Hasher._seed
let perturbation = bucketCount
_storage.seed = (seed.0 ^ UInt64(truncatingIfNeeded: perturbation), seed.1)
}
// Forwarding the individual fields of the storage in various forms
@inlinable // FIXME(sil-serialize-all)
internal var bucketCount: Int {
return _assumeNonNegative(_storage.bucketCount)
}
@inlinable // FIXME(sil-serialize-all)
internal var count: Int {
set {
_storage.count = newValue
}
get {
return _assumeNonNegative(_storage.count)
}
}
@inlinable // FIXME(sil-serialize-all)
internal
var _initializedHashtableEntriesBitMapBuffer: UnsafeMutablePointer<UInt> {
return _storage._initializedHashtableEntriesBitMapBuffer
}
// This API is unsafe and needs a `_fixLifetime` in the caller.
@inlinable // FIXME(sil-serialize-all)
internal var keys: UnsafeMutablePointer<Element> {
return _storage.keys.assumingMemoryBound(to: Element.self)
}
/// Constructs a buffer adopting the given storage.
@inlinable // FIXME(sil-serialize-all)
internal init(_storage: _RawNativeSetStorage) {
self._storage = _storage
}
/// Constructs an instance from the empty singleton.
@inlinable // FIXME(sil-serialize-all)
internal init() {
self._storage = _RawNativeSetStorage.empty
}
// Most of the implementation of the _SetBuffer protocol,
// but only the parts that don't actually rely on hashing.
@inlinable // FIXME(sil-serialize-all)
@inline(__always)
internal func key(at i: Int) -> Element {
_sanityCheck(i >= 0 && i < bucketCount)
_sanityCheck(isInitializedEntry(at: i))
defer { _fixLifetime(self) }
let res = (keys + i).pointee
return res
}
#if _runtime(_ObjC)
/// Returns the key at the given Index, bridged.
///
/// Intended for use with verbatim bridgeable keys.
@inlinable // FIXME(sil-serialize-all)
internal func bridgedKey(at index: Index) -> AnyObject {
let k = key(at: index.offset)
return _bridgeAnythingToObjectiveC(k)
}
/// Returns the value at the given Index, bridged.
///
/// Intended for use with verbatim bridgeable keys.
@inlinable // FIXME(sil-serialize-all)
internal func bridgedValue(at index: Index) -> AnyObject {
let v = value(at: index.offset)
return _bridgeAnythingToObjectiveC(v)
}
#endif
@inlinable // FIXME(sil-serialize-all)
internal func isInitializedEntry(at i: Int) -> Bool {
_sanityCheck(i >= 0 && i < bucketCount)
defer { _fixLifetime(self) }
return _storage.initializedEntries[i]
}
@usableFromInline @_transparent
internal func destroyEntry(at i: Int) {
_sanityCheck(isInitializedEntry(at: i))
defer { _fixLifetime(self) }
(keys + i).deinitialize(count: 1)
_storage.initializedEntries[i] = false
}
@usableFromInline @_transparent
internal func initializeKey(_ k: Element, at i: Int) {
_sanityCheck(!isInitializedEntry(at: i))
defer { _fixLifetime(self) }
(keys + i).initialize(to: k)
_storage.initializedEntries[i] = true
}
@usableFromInline @_transparent
internal func moveInitializeEntry(from: Buffer, at: Int, toEntryAt: Int) {
_sanityCheck(!isInitializedEntry(at: toEntryAt))
defer { _fixLifetime(self) }
(keys + toEntryAt).initialize(to: (from.keys + at).move())
from._storage.initializedEntries[at] = false
_storage.initializedEntries[toEntryAt] = true
}
/// Alias for key(at:) in Sets for better code reuse
@usableFromInline @_transparent
internal func value(at i: Int) -> Element {
return key(at: i)
}
@inlinable // FIXME(sil-serialize-all)
internal func setKey(_ key: Element, at i: Int) {
_sanityCheck(i >= 0 && i < bucketCount)
_sanityCheck(isInitializedEntry(at: i))
defer { _fixLifetime(self) }
(keys + i).pointee = key
}
@inlinable // FIXME(sil-serialize-all)
internal var startIndex: Index {
// We start at "index after -1" instead of "0" because we need to find the
// first occupied slot.
return index(after: Index(offset: -1))
}
@inlinable // FIXME(sil-serialize-all)
internal var endIndex: Index {
return Index(offset: bucketCount)
}
@inlinable // FIXME(sil-serialize-all)
internal func index(after i: Index) -> Index {
_precondition(i != endIndex)
var idx = i.offset + 1
while idx < bucketCount && !isInitializedEntry(at: idx) {
idx += 1
}
return Index(offset: idx)
}
@inlinable // FIXME(sil-serialize-all)
internal func formIndex(after i: inout Index) {
i = index(after: i)
}
@inlinable // FIXME(sil-serialize-all)
internal func assertingGet(at i: Index) -> Element {
_precondition(i.offset >= 0 && i.offset < bucketCount)
_precondition(
isInitializedEntry(at: i.offset),
"Attempting to access Set elements using an invalid Index")
let key = self.key(at: i.offset)
return key
}
}
extension _NativeSetBuffer/*: _SetBuffer*/ where Element: Hashable {
@usableFromInline
internal typealias HashTypedStorage =
_HashableTypedNativeSetStorage<Element>
@inlinable // FIXME(sil-serialize-all)
@inline(__always)
internal init(minimumCapacity: Int) {
let bucketCount = _NativeSetBuffer.bucketCount(
forCapacity: minimumCapacity,
maxLoadFactorInverse: _hashContainerDefaultMaxLoadFactorInverse)
self.init(bucketCount: bucketCount)
}
@inlinable // FIXME(sil-serialize-all)
@inline(__always)
internal init(bucketCount: Int) {
// Actual bucket count is the next power of 2 greater than or equal to
// bucketCount. Make sure that is representable.
_sanityCheck(bucketCount <= (Int.max >> 1) + 1)
let buckets = 1 &<< ((Swift.max(bucketCount, 2) - 1)._binaryLogarithm() + 1)
self.init(_exactBucketCount: buckets)
}
/// Create a buffer instance with room for at least 'bucketCount' entries,
/// marking all entries invalid.
@inlinable // FIXME(sil-serialize-all)
internal init(_exactBucketCount bucketCount: Int) {
let bitmapWordCount = _UnsafeBitMap.sizeInWords(forSizeInBits: bucketCount)
let storage = Builtin.allocWithTailElems_2(HashTypedStorage.self,
bitmapWordCount._builtinWordValue, UInt.self,
bucketCount._builtinWordValue, Element.self)
self.init(_exactBucketCount: bucketCount, storage: storage)
}
#if _runtime(_ObjC)
@usableFromInline
internal func bridged() -> _NSSet {
// We can zero-cost bridge if our keys are verbatim
// or if we're the empty singleton.
// Temporary var for SOME type safety before a cast.
let nsSet: _NSSetCore
if _isBridgedVerbatimToObjectiveC(Element.self) ||
self._storage === _RawNativeSetStorage.empty {
nsSet = self._storage
} else {
nsSet = _SwiftDeferredNSSet(nativeBuffer: self)
}
// Cast from "minimal NSSet" to "NSSet"
// Note that if you actually ask Swift for this cast, it will fail.
// Never trust a shadow protocol!
return unsafeBitCast(nsSet, to: _NSSet.self)
}
#endif
/// A textual representation of `self`.
@inlinable // FIXME(sil-serialize-all)
internal var description: String {
var result = ""
#if INTERNAL_CHECKS_ENABLED
for i in 0..<bucketCount {
if isInitializedEntry(at: i) {
let key = self.key(at: i)
result += "bucket \(i), ideal bucket = \(_bucket(key)), key = \(key)\n"
} else {
result += "bucket \(i), empty\n"
}
}
#endif
return result
}
@inlinable // FIXME(sil-serialize-all)
internal var _bucketMask: Int {
// The bucket count is not negative, therefore subtracting 1 will not
// overflow.
return bucketCount &- 1
}
@inlinable // FIXME(sil-serialize-all)
@inline(__always) // For performance reasons.
internal func _bucket(_ k: Element) -> Int {
return k._rawHashValue(seed: _storage.seed) & _bucketMask
}
@inlinable // FIXME(sil-serialize-all)
internal func _index(after bucket: Int) -> Int {
// Bucket is within 0 and bucketCount. Therefore adding 1 does not overflow.
return (bucket &+ 1) & _bucketMask
}
@inlinable // FIXME(sil-serialize-all)
internal func _prev(_ bucket: Int) -> Int {
// Bucket is not negative. Therefore subtracting 1 does not overflow.
return (bucket &- 1) & _bucketMask
}
/// Search for a given key starting from the specified bucket.
///
/// If the key is not present, returns the position where it could be
/// inserted.
@inlinable // FIXME(sil-serialize-all)
@inline(__always)
internal func _find(_ key: Element, startBucket: Int)
-> (pos: Index, found: Bool) {
var bucket = startBucket
// The invariant guarantees there's always a hole, so we just loop
// until we find one
while true {
let isHole = !isInitializedEntry(at: bucket)
if isHole {
return (Index(offset: bucket), false)
}
if self.key(at: bucket) == key {
return (Index(offset: bucket), true)
}
bucket = _index(after: bucket)
}
}
@usableFromInline @_transparent
internal static func bucketCount(
forCapacity capacity: Int,
maxLoadFactorInverse: Double
) -> Int {
// `capacity + 1` below ensures that we don't fill in the last hole
return max(Int((Double(capacity) * maxLoadFactorInverse).rounded(.up)),
capacity + 1)
}
/// Buffer should be uniquely referenced.
/// The `key` should not be present in the Set.
/// This function does *not* update `count`.
@inlinable // FIXME(sil-serialize-all)
internal func unsafeAddNew(key newKey: Element) {
let (i, found) = _find(newKey, startBucket: _bucket(newKey))
_precondition(
!found, "Duplicate element found in Set. Elements may have been mutated after insertion")
initializeKey(newKey, at: i.offset)
}
@inlinable // FIXME(sil-serialize-all)
internal static func fromArray(_ elements: [Element])
-> Buffer
{
if elements.isEmpty {
return Buffer()
}
var nativeBuffer = Buffer(minimumCapacity: elements.count)
var count = 0
for key in elements {
let (i, found) =
nativeBuffer._find(key, startBucket: nativeBuffer._bucket(key))
if found {
continue
}
nativeBuffer.initializeKey(key, at: i.offset)
count += 1
}
nativeBuffer.count = count
return nativeBuffer
}
}
extension _NativeSetBuffer/*: _SetBuffer*/ where Element: Hashable {
//
// _SetBuffer conformance
//
@inlinable // FIXME(sil-serialize-all)
@inline(__always)
internal func index(forKey key: Element) -> Index? {
if count == 0 {
// Fast path that avoids computing the hash of the key.
return nil
}
let (i, found) = _find(key, startBucket: _bucket(key))
return found ? i : nil
}
@inlinable // FIXME(sil-serialize-all)
@inline(__always)
internal func maybeGet(_ key: Element) -> Element? {
if count == 0 {
// Fast path that avoids computing the hash of the key.
return nil
}
let (i, found) = _find(key, startBucket: _bucket(key))
if found {
return self.key(at: i.offset)
}
return nil
}
}
#if _runtime(_ObjC)
/// An NSEnumerator that works with any NativeSetBuffer of
/// verbatim bridgeable elements. Used by the various NSSet impls.
final internal class _NativeSetNSEnumerator<Element>
: _SwiftNativeNSEnumerator, _NSEnumerator {
internal typealias Buffer = _NativeSetBuffer<Element>
internal typealias Index = _NativeSetIndex<Element>
internal override required init() {
_sanityCheckFailure("don't call this designated initializer")
}
internal init(_ buffer: Buffer) {
self.buffer = buffer
nextIndex = buffer.startIndex
endIndex = buffer.endIndex
}
internal var buffer: Buffer
internal var nextIndex: Index
internal var endIndex: Index
//
// NSEnumerator implementation.
//
// Do not call any of these methods from the standard library!
//
@objc
internal func nextObject() -> AnyObject? {
if nextIndex == endIndex {
return nil
}
let key = buffer.bridgedKey(at: nextIndex)
buffer.formIndex(after: &nextIndex)
return key
}
@objc(countByEnumeratingWithState:objects:count:)
internal func countByEnumerating(
with state: UnsafeMutablePointer<_SwiftNSFastEnumerationState>,
objects: UnsafeMutablePointer<AnyObject>,
count: Int
) -> Int {
var theState = state.pointee
if theState.state == 0 {
theState.state = 1 // Arbitrary non-zero value.
theState.itemsPtr = AutoreleasingUnsafeMutablePointer(objects)
theState.mutationsPtr = _fastEnumerationStorageMutationsPtr
}
if nextIndex == endIndex {
state.pointee = theState
return 0
}
// Return only a single element so that code can start iterating via fast
// enumeration, terminate it, and continue via NSEnumerator.
let key = buffer.bridgedKey(at: nextIndex)
buffer.formIndex(after: &nextIndex)
let unmanagedObjects = _UnmanagedAnyObjectArray(objects)
unmanagedObjects[0] = key
state.pointee = theState
return 1
}
}
#endif
#if _runtime(_ObjC)
/// This class exists for Objective-C bridging. It holds a reference to a
/// NativeSetBuffer, and can be upcast to NSSelf when bridging is necessary.
/// This is the fallback implementation for situations where toll-free bridging
/// isn't possible. On first access, a NativeSetBuffer of AnyObject will be
/// constructed containing all the bridged elements.
final internal class _SwiftDeferredNSSet<Element: Hashable>
: _SwiftNativeNSSet, _NSSetCore {
internal init(nativeBuffer: _NativeSetBuffer<Element>) {
self.nativeBuffer = nativeBuffer
super.init()
}
// This stored property should be stored at offset zero. We perform atomic
// operations on it.
//
// Do not access this property directly.
@nonobjc
internal var _heapStorageBridged_DoNotUse: AnyObject?
/// The unbridged elements.
internal var nativeBuffer: _NativeSetBuffer<Element>
@objc(copyWithZone:)
internal func copy(with zone: _SwiftNSZone?) -> AnyObject {
// Instances of this class should be visible outside of standard library as
// having `NSSet` type, which is immutable.
return self
}
//
// NSSet implementation.
//
// Do not call any of these methods from the standard library! Use only
// `nativeBuffer`.
//
@objc
internal required init(objects: UnsafePointer<AnyObject?>, count: Int) {
_sanityCheckFailure("don't call this designated initializer")
}
@objc
internal func member(_ object: AnyObject) -> AnyObject? {
guard let element =
_conditionallyBridgeFromObjectiveC(object, Element.self)
else { return nil }
let (i, found) = nativeBuffer._find(
element, startBucket: nativeBuffer._bucket(element))
if found {
bridgeEverything()
return bridgedBuffer.value(at: i.offset)
}
return nil
}
@objc
internal func objectEnumerator() -> _NSEnumerator {
return enumerator()
}
/// Returns the pointer to the stored property, which contains bridged
/// Set elements.
@nonobjc
internal var _heapStorageBridgedPtr: UnsafeMutablePointer<AnyObject?> {
return _getUnsafePointerToStoredProperties(self).assumingMemoryBound(
to: Optional<AnyObject>.self)
}
/// The buffer for bridged Set elements, if present.
@nonobjc
internal var _bridgedStorage: _RawNativeSetStorage? {
get {
if let ref = _stdlib_atomicLoadARCRef(object: _heapStorageBridgedPtr) {
return unsafeDowncast(ref, to: _RawNativeSetStorage.self)
}
return nil
}
}
/// Attach a buffer for bridged Set elements.
@nonobjc
internal func _initializeHeapStorageBridged(_ newStorage: AnyObject) {
_stdlib_atomicInitializeARCRef(
object: _heapStorageBridgedPtr, desired: newStorage)
}
/// Returns the bridged Set values.
internal var bridgedBuffer: _NativeSetBuffer<AnyObject> {
return _NativeSetBuffer(_storage: _bridgedStorage!)
}
@nonobjc
internal func bridgeEverything() {
if _fastPath(_bridgedStorage != nil) {
return
}
// FIXME: rdar://problem/19486139 (split bridged buffers for keys and values)
// We bridge keys and values unconditionally here, even if one of them
// actually is verbatim bridgeable (e.g. Dictionary<Int, AnyObject>).
// Investigate only allocating the buffer for a Set in this case.
// Create buffer for bridged data.
let bridged = _NativeSetBuffer<AnyObject>(
_exactBucketCount: nativeBuffer.bucketCount,
unhashable: ())
// Bridge everything.
for i in 0..<nativeBuffer.bucketCount {
if nativeBuffer.isInitializedEntry(at: i) {
let key = _bridgeAnythingToObjectiveC(nativeBuffer.key(at: i))
bridged.initializeKey(key, at: i)
}
}
// Atomically put the bridged elements in place.
_initializeHeapStorageBridged(bridged._storage)
}
@objc
internal var count: Int {
return nativeBuffer.count
}
@objc
internal func enumerator() -> _NSEnumerator {
bridgeEverything()
return _NativeSetNSEnumerator<AnyObject>(bridgedBuffer)
}
@objc(countByEnumeratingWithState:objects:count:)
internal func countByEnumerating(
with state: UnsafeMutablePointer<_SwiftNSFastEnumerationState>,
objects: UnsafeMutablePointer<AnyObject>?,
count: Int
) -> Int {
var theState = state.pointee
if theState.state == 0 {
theState.state = 1 // Arbitrary non-zero value.
theState.itemsPtr = AutoreleasingUnsafeMutablePointer(objects)
theState.mutationsPtr = _fastEnumerationStorageMutationsPtr
theState.extra.0 = CUnsignedLong(nativeBuffer.startIndex.offset)
}
// Test 'objects' rather than 'count' because (a) this is very rare anyway,
// and (b) the optimizer should then be able to optimize away the
// unwrapping check below.
if _slowPath(objects == nil) {
return 0
}
let unmanagedObjects = _UnmanagedAnyObjectArray(objects!)
var currIndex = _NativeSetIndex<Element>(
offset: Int(theState.extra.0))
let endIndex = nativeBuffer.endIndex
var stored = 0
// Only need to bridge once, so we can hoist it out of the loop.
if (currIndex != endIndex) {
bridgeEverything()
}
for i in 0..<count {
if (currIndex == endIndex) {
break
}
let bridgedKey = bridgedBuffer.key(at: currIndex.offset)
unmanagedObjects[i] = bridgedKey
stored += 1
nativeBuffer.formIndex(after: &currIndex)
}
theState.extra.0 = CUnsignedLong(currIndex.offset)
state.pointee = theState
return stored
}
}
#else
final internal class _SwiftDeferredNSSet<Element: Hashable> { }
#endif
#if _runtime(_ObjC)
@usableFromInline
@_fixed_layout
internal struct _CocoaSetBuffer: _SetBuffer {
@usableFromInline
internal var cocoaSet: _NSSet
@inlinable // FIXME(sil-serialize-all)
internal init(cocoaSet: _NSSet) {
self.cocoaSet = cocoaSet
}
@usableFromInline
internal typealias Index = _CocoaSetIndex
@inlinable // FIXME(sil-serialize-all)
internal var startIndex: Index {
return Index(cocoaSet, startIndex: ())
}
@inlinable // FIXME(sil-serialize-all)
internal var endIndex: Index {
return Index(cocoaSet, endIndex: ())
}
@inlinable // FIXME(sil-serialize-all)
internal func index(after i: Index) -> Index {
return i.successor()
}
@inlinable // FIXME(sil-serialize-all)
internal func formIndex(after i: inout Index) {
// FIXME: swift-3-indexing-model: optimize if possible.
i = i.successor()
}
@inlinable // FIXME(sil-serialize-all)
internal func index(forKey key: AnyObject) -> Index? {
// Fast path that does not involve creating an array of all keys. In case
// the key is present, this lookup is a penalty for the slow path, but the
// potential savings are significant: we could skip a memory allocation and
// a linear search.
if maybeGet(key) == nil {
return nil
}
let allKeys = _stdlib_NSSet_allObjects(cocoaSet)
var keyIndex = -1
for i in 0..<allKeys.value {
if _stdlib_NSObject_isEqual(key, allKeys[i]) {
keyIndex = i
break
}
}
_sanityCheck(keyIndex >= 0,
"Key was found in fast path, but not found later?")
return Index(cocoaSet, allKeys, keyIndex)
}
@inlinable // FIXME(sil-serialize-all)
internal var count: Int {
return cocoaSet.count
}
@inlinable // FIXME(sil-serialize-all)
internal func assertingGet(at i: Index) -> AnyObject {
let value: AnyObject? = i.allKeys[i.currentKeyIndex]
_sanityCheck(value != nil, "Item not found in underlying NSSet")
return value!
}
@inlinable // FIXME(sil-serialize-all)
@inline(__always)
internal func maybeGet(_ key: AnyObject) -> AnyObject? {
return cocoaSet.member(key)
}
@usableFromInline
internal func _toNative<Element: Hashable>(
bucketCount: Int
) -> _NativeSetBuffer<Element> {
let cocoaSet = self.cocoaSet
var newNativeBuffer = _NativeSetBuffer<Element>(bucketCount: bucketCount)
let oldCocoaIterator = _CocoaSetIterator(cocoaSet)
while let element = oldCocoaIterator.next() {
newNativeBuffer.unsafeAddNew(
key: _forceBridgeFromObjectiveC(element, Element.self))
}
newNativeBuffer.count = cocoaSet.count
return newNativeBuffer
}
}
#endif
@usableFromInline
@_frozen
internal enum _VariantSetBuffer<Element: Hashable>: _SetBuffer {
@usableFromInline
internal typealias NativeBuffer = _NativeSetBuffer<Element>
@usableFromInline
internal typealias NativeIndex = _NativeSetIndex<Element>
#if _runtime(_ObjC)
@usableFromInline
internal typealias CocoaBuffer = _CocoaSetBuffer
#endif
@usableFromInline
internal typealias SelfType = _VariantSetBuffer
case native(NativeBuffer)
#if _runtime(_ObjC)
case cocoa(CocoaBuffer)
#endif
@usableFromInline @_transparent
internal var guaranteedNative: Bool {
return _canBeClass(Element.self) == 0
}
@inlinable // FIXME(sil-serialize-all)
internal mutating func isUniquelyReferenced() -> Bool {
// Note that &self drills down through .native(NativeBuffer) to the first
// property in NativeBuffer, which is the reference to the storage.
if _fastPath(guaranteedNative) {
return _isUnique_native(&self)
}
switch self {
case .native:
return _isUnique_native(&self)
#if _runtime(_ObjC)
case .cocoa:
// Don't consider Cocoa buffer mutable, even if it is mutable and is
// uniquely referenced.
return false
#endif
}
}
@inlinable // FIXME(sil-serialize-all)
internal var asNative: NativeBuffer {
get {
switch self {
case .native(let buffer):
return buffer
#if _runtime(_ObjC)
case .cocoa:
_sanityCheckFailure("internal error: not backed by native buffer")
#endif
}
}
set {
self = .native(newValue)
}
}
@inlinable // FIXME(sil-serialize-all)
internal mutating func ensureNativeBuffer() {
#if _runtime(_ObjC)
if _fastPath(guaranteedNative) { return }
if case .cocoa(let cocoaBuffer) = self {
migrateDataToNativeBuffer(cocoaBuffer)
}
#endif
}
#if _runtime(_ObjC)
@inlinable // FIXME(sil-serialize-all)
internal var asCocoa: CocoaBuffer {
switch self {
case .native:
_sanityCheckFailure("internal error: not backed by NSSet")
case .cocoa(let cocoaBuffer):
return cocoaBuffer
}
}
#endif
/// Return true if self is native.
@inlinable // FIXME(sil-serialize-all)
internal var _isNative: Bool {
#if _runtime(_ObjC)
switch self {
case .native:
return true
case .cocoa:
return false
}
#else
return true
#endif
}
@inline(__always)
@inlinable // FIXME(sil-serialize-all)
internal mutating func ensureUniqueNativeBufferNative(
withBucketCount desiredBucketCount: Int
) -> (reallocated: Bool, capacityChanged: Bool) {
let oldBucketCount = asNative.bucketCount
if oldBucketCount >= desiredBucketCount && isUniquelyReferenced() {
return (reallocated: false, capacityChanged: false)
}
let oldNativeBuffer = asNative
var newNativeBuffer = NativeBuffer(bucketCount: desiredBucketCount)
let newBucketCount = newNativeBuffer.bucketCount
for i in 0..<oldBucketCount {
if oldNativeBuffer.isInitializedEntry(at: i) {
if oldBucketCount == newBucketCount {
let key = oldNativeBuffer.key(at: i)
newNativeBuffer.initializeKey(key, at: i)
} else {
let key = oldNativeBuffer.key(at: i)
newNativeBuffer.unsafeAddNew(key: key)
}
}
}
newNativeBuffer.count = oldNativeBuffer.count
self = .native(newNativeBuffer)
return (reallocated: true,
capacityChanged: oldBucketCount != newBucketCount)
}
@inline(__always)
@inlinable // FIXME(sil-serialize-all)
internal mutating func ensureUniqueNativeBuffer(
withCapacity minimumCapacity: Int
) -> (reallocated: Bool, capacityChanged: Bool) {
let bucketCount = NativeBuffer.bucketCount(
forCapacity: minimumCapacity,
maxLoadFactorInverse: _hashContainerDefaultMaxLoadFactorInverse)
return ensureUniqueNativeBuffer(withBucketCount: bucketCount)
}
/// Ensure this we hold a unique reference to a native buffer
/// having at least `minimumCapacity` elements.
@inlinable // FIXME(sil-serialize-all)
internal mutating func ensureUniqueNativeBuffer(
withBucketCount desiredBucketCount: Int
) -> (reallocated: Bool, capacityChanged: Bool) {
#if _runtime(_ObjC)
// This is a performance optimization that was put in to ensure that we did
// not make a copy of self to call _isNative over the entire if region
// causing at -Onone the uniqueness check to fail. This code used to be:
//
// if _isNative {
// return ensureUniqueNativeBufferNative(
// withBucketCount: desiredBucketCount)
// }
//
// SR-6437
let n = _isNative
if n {
return ensureUniqueNativeBufferNative(withBucketCount: desiredBucketCount)
}
switch self {
case .native:
fatalError("This should have been handled earlier")
case .cocoa(let cocoaBuffer):
self = .native(cocoaBuffer._toNative(bucketCount: desiredBucketCount))
return (reallocated: true, capacityChanged: true)
}
#else
return ensureUniqueNativeBufferNative(withBucketCount: desiredBucketCount)
#endif
}
#if _runtime(_ObjC)
@usableFromInline
internal mutating func migrateDataToNativeBuffer(
_ cocoaBuffer: _CocoaSetBuffer
) {
let allocated = ensureUniqueNativeBuffer(
withCapacity: cocoaBuffer.count).reallocated
_sanityCheck(allocated, "failed to allocate native Set buffer")
}
#endif
/// Reserves enough space for the specified number of elements to be stored
/// without reallocating additional storage.
@inlinable // FIXME(sil-serialize-all)
internal mutating func reserveCapacity(_ capacity: Int) {
_ = ensureUniqueNativeBuffer(withCapacity: capacity)
}
/// The number of elements that can be stored without expanding the current
/// storage.
///
/// For bridged storage, this is equal to the current count of the
/// collection, since any addition will trigger a copy of the elements into
/// newly allocated storage. For native storage, this is the element count
/// at which adding any more elements will exceed the load factor.
@inlinable // FIXME(sil-serialize-all)
internal var capacity: Int {
switch self {
case .native:
return Int(Double(asNative.bucketCount) /
_hashContainerDefaultMaxLoadFactorInverse)
#if _runtime(_ObjC)
case .cocoa(let cocoaBuffer):
return cocoaBuffer.count
#endif
}
}
//
// _SetBuffer conformance
//
@usableFromInline
internal typealias Index = SetIndex<Element>
@inlinable // FIXME(sil-serialize-all)
internal var startIndex: Index {
if _fastPath(guaranteedNative) {
return ._native(asNative.startIndex)
}
switch self {
case .native:
return ._native(asNative.startIndex)
#if _runtime(_ObjC)
case .cocoa(let cocoaBuffer):
return ._cocoa(cocoaBuffer.startIndex)
#endif
}
}
@inlinable // FIXME(sil-serialize-all)
internal var endIndex: Index {
if _fastPath(guaranteedNative) {
return ._native(asNative.endIndex)
}
switch self {
case .native:
return ._native(asNative.endIndex)
#if _runtime(_ObjC)
case .cocoa(let cocoaBuffer):
return ._cocoa(cocoaBuffer.endIndex)
#endif
}
}
@inlinable // FIXME(sil-serialize-all)
internal func index(after i: Index) -> Index {
if _fastPath(guaranteedNative) {
return ._native(asNative.index(after: i._nativeIndex))
}
switch self {
case .native:
return ._native(asNative.index(after: i._nativeIndex))
#if _runtime(_ObjC)
case .cocoa(let cocoaBuffer):
return ._cocoa(cocoaBuffer.index(after: i._cocoaIndex))
#endif
}
}
@inlinable // FIXME(sil-serialize-all)
internal func formIndex(after i: inout Index) {
// FIXME: swift-3-indexing-model: optimize if possible.
i = index(after: i)
}
@inlinable // FIXME(sil-serialize-all)
@inline(__always)
internal func index(forKey key: Element) -> Index? {
if _fastPath(guaranteedNative) {
if let nativeIndex = asNative.index(forKey: key) {
return ._native(nativeIndex)
}
return nil
}
switch self {
case .native:
if let nativeIndex = asNative.index(forKey: key) {
return ._native(nativeIndex)
}
return nil
#if _runtime(_ObjC)
case .cocoa(let cocoaBuffer):
let anyObjectKey: AnyObject = _bridgeAnythingToObjectiveC(key)
if let cocoaIndex = cocoaBuffer.index(forKey: anyObjectKey) {
return ._cocoa(cocoaIndex)
}
return nil
#endif
}
}
@inlinable // FIXME(sil-serialize-all)
internal func assertingGet(at i: Index) -> Element {
if _fastPath(guaranteedNative) {
return asNative.assertingGet(at: i._nativeIndex)
}
switch self {
case .native:
return asNative.assertingGet(at: i._nativeIndex)
#if _runtime(_ObjC)
case .cocoa(let cocoaBuffer):
let anyObjectValue = cocoaBuffer.assertingGet(at: i._cocoaIndex)
let nativeValue = _forceBridgeFromObjectiveC(anyObjectValue, Element.self)
return nativeValue
#endif
}
}
#if _runtime(_ObjC)
@inline(never)
@usableFromInline
internal static func maybeGetFromCocoaBuffer(
_ cocoaBuffer: CocoaBuffer, forKey key: Element
) -> Element? {
let anyObjectKey: AnyObject = _bridgeAnythingToObjectiveC(key)
if let anyObjectValue = cocoaBuffer.maybeGet(anyObjectKey) {
return _forceBridgeFromObjectiveC(anyObjectValue, Element.self)
}
return nil
}
#endif
@inlinable // FIXME(sil-serialize-all)
@inline(__always)
internal func maybeGet(_ key: Element) -> Element? {
if _fastPath(guaranteedNative) {
return asNative.maybeGet(key)
}
switch self {
case .native:
return asNative.maybeGet(key)
#if _runtime(_ObjC)
case .cocoa(let cocoaBuffer):
return SelfType.maybeGetFromCocoaBuffer(cocoaBuffer, forKey: key)
#endif
}
}
@inlinable // FIXME(sil-serialize-all)
internal mutating func nativeUpdate(
with key: Element
) -> Element? {
var (i, found) = asNative._find(key, startBucket: asNative._bucket(key))
let minBuckets = found
? asNative.bucketCount
: NativeBuffer.bucketCount(
forCapacity: asNative.count + 1,
maxLoadFactorInverse: _hashContainerDefaultMaxLoadFactorInverse)
let (_, capacityChanged) = ensureUniqueNativeBuffer(
withBucketCount: minBuckets)
if capacityChanged {
i = asNative._find(key, startBucket: asNative._bucket(key)).pos
}
let old: Element? = found ? asNative.key(at: i.offset) : nil
if found {
asNative.setKey(key, at: i.offset)
} else {
asNative.initializeKey(key, at: i.offset)
asNative.count += 1
}
return old
}
@inlinable // FIXME(sil-serialize-all)
@discardableResult
internal mutating func update(with value: Element) -> Element? {
if _fastPath(guaranteedNative) {
return nativeUpdate(with: value)
}
switch self {
case .native:
return nativeUpdate(with: value)
#if _runtime(_ObjC)
case .cocoa(let cocoaBuffer):
migrateDataToNativeBuffer(cocoaBuffer)
return nativeUpdate(with: value)
#endif
}
}
@inlinable // FIXME(sil-serialize-all)
@discardableResult
internal mutating func insert(
_ key: Element
) -> (inserted: Bool, memberAfterInsert: Element) {
ensureNativeBuffer()
var (i, found) = asNative._find(key, startBucket: asNative._bucket(key))
if found {
return (inserted: false, memberAfterInsert: asNative.key(at: i.offset))
}
let minCapacity = asNative.count + 1
let (_, capacityChanged) = ensureUniqueNativeBuffer(
withCapacity: minCapacity)
if capacityChanged {
i = asNative._find(key, startBucket: asNative._bucket(key)).pos
}
asNative.initializeKey(key, at: i.offset)
asNative.count += 1
return (inserted: true, memberAfterInsert: key)
}
/// - parameter idealBucket: The ideal bucket for the element being deleted.
/// - parameter offset: The offset of the element that will be deleted.
/// Precondition: there should be an initialized entry at offset.
@inlinable // FIXME(sil-serialize-all)
internal mutating func nativeDelete(
_ nativeBuffer: NativeBuffer, idealBucket: Int, offset: Int
) {
_sanityCheck(
nativeBuffer.isInitializedEntry(at: offset), "expected initialized entry")
var nativeBuffer = nativeBuffer
// remove the element
nativeBuffer.destroyEntry(at: offset)
nativeBuffer.count -= 1
// If we've put a hole in a chain of contiguous elements, some
// element after the hole may belong where the new hole is.
var hole = offset
// Find the first bucket in the contiguous chain
var start = idealBucket
while nativeBuffer.isInitializedEntry(at: nativeBuffer._prev(start)) {
start = nativeBuffer._prev(start)
}
// Find the last bucket in the contiguous chain
var lastInChain = hole
var b = nativeBuffer._index(after: lastInChain)
while nativeBuffer.isInitializedEntry(at: b) {
lastInChain = b
b = nativeBuffer._index(after: b)
}
// Relocate out-of-place elements in the chain, repeating until
// none are found.
while hole != lastInChain {
// Walk backwards from the end of the chain looking for
// something out-of-place.
var b = lastInChain
while b != hole {
let idealBucket = nativeBuffer._bucket(nativeBuffer.key(at: b))
// Does this element belong between start and hole? We need
// two separate tests depending on whether [start, hole] wraps
// around the end of the storage
let c0 = idealBucket >= start
let c1 = idealBucket <= hole
if start <= hole ? (c0 && c1) : (c0 || c1) {
break // Found it
}
b = nativeBuffer._prev(b)
}
if b == hole { // No out-of-place elements found; we're done adjusting
break
}
// Move the found element into the hole
nativeBuffer.moveInitializeEntry(
from: nativeBuffer,
at: b,
toEntryAt: hole)
hole = b
}
}
@inlinable // FIXME(sil-serialize-all)
internal mutating func nativeRemove(_ key: Element) -> Element? {
var idealBucket = asNative._bucket(key)
var (index, found) = asNative._find(key, startBucket: idealBucket)
// Fast path: if the key is not present, we will not mutate the set,
// so don't force unique buffer.
if !found {
return nil
}
// This is a performance optimization that was put in to ensure that we
// did not make a copy of self to call asNative.bucketCount over
// ensureUniqueNativeBefore causing at -Onone the uniqueness check to
// fail. This code used to be:
//
// ... = ensureUniqueNativeBuffer(withBucketCount: asNative.bucketCount)
//
// SR-6437
let bucketCount = asNative.bucketCount
let (_, capacityChanged) = ensureUniqueNativeBuffer(
withBucketCount: bucketCount)
let nativeBuffer = asNative
if capacityChanged {
idealBucket = nativeBuffer._bucket(key)
(index, found) = nativeBuffer._find(key, startBucket: idealBucket)
_sanityCheck(found, "key was lost during buffer migration")
}
let oldValue = nativeBuffer.key(at: index.offset)
nativeDelete(nativeBuffer, idealBucket: idealBucket,
offset: index.offset)
return oldValue
}
@inlinable // FIXME(sil-serialize-all)
internal mutating func nativeRemove(at nativeIndex: NativeIndex) -> Element {
// This is a performance optimization that was put in to ensure that we did
// not make a copy of self to call asNative.bucketCount over
// ensureUniqueNativeBefore causing at -Onone the uniqueness check to
// fail. This code used to be:
//
// _ = ensureUniqueNativeBuffer(withBucketCount: asNative.bucketCount)
//
// SR-6437
let bucketCount = asNative.bucketCount
// The provided index should be valid, so we will always mutating the
// set buffer. Request unique buffer.
_ = ensureUniqueNativeBuffer(withBucketCount: bucketCount)
let nativeBuffer = asNative
let result = nativeBuffer.assertingGet(at: nativeIndex)
let key = result
nativeDelete(nativeBuffer, idealBucket: nativeBuffer._bucket(key),
offset: nativeIndex.offset)
return result
}
@inlinable // FIXME(sil-serialize-all)
@discardableResult
internal mutating func remove(at index: Index) -> Element {
if _fastPath(guaranteedNative) {
return nativeRemove(at: index._nativeIndex)
}
switch self {
case .native:
return nativeRemove(at: index._nativeIndex)
#if _runtime(_ObjC)
case .cocoa(let cocoaBuffer):
// We have to migrate the data first. But after we do so, the Cocoa
// index becomes useless, so get the key first.
//
// FIXME(performance): fuse data migration and element deletion into one
// operation.
let index = index._cocoaIndex
let anyObjectKey: AnyObject = index.allKeys[index.currentKeyIndex]
migrateDataToNativeBuffer(cocoaBuffer)
let key = _forceBridgeFromObjectiveC(anyObjectKey, Element.self)
let old = nativeRemove(key)
_sanityCheck(key == old, "bridging did not preserve equality")
return key
#endif
}
}
@inlinable // FIXME(sil-serialize-all)
@discardableResult
internal mutating func remove(_ member: Element) -> Element? {
if _fastPath(guaranteedNative) {
return nativeRemove(member)
}
switch self {
case .native:
return nativeRemove(member)
#if _runtime(_ObjC)
case .cocoa(let cocoaBuffer):
let cocoaMember = _bridgeAnythingToObjectiveC(member)
if cocoaBuffer.maybeGet(cocoaMember) == nil {
return nil
}
migrateDataToNativeBuffer(cocoaBuffer)
return nativeRemove(member)
#endif
}
}
@inlinable // FIXME(sil-serialize-all)
internal mutating func nativeRemoveAll() {
if !isUniquelyReferenced() {
asNative = NativeBuffer(_exactBucketCount: asNative.bucketCount)
return
}
// We have already checked for the empty dictionary case and unique
// reference, so we will always mutate the dictionary buffer.
var nativeBuffer = asNative
for b in 0..<nativeBuffer.bucketCount {
if nativeBuffer.isInitializedEntry(at: b) {
nativeBuffer.destroyEntry(at: b)
}
}
nativeBuffer.count = 0
}
@inlinable // FIXME(sil-serialize-all)
internal mutating func removeAll(keepingCapacity keepCapacity: Bool) {
if count == 0 {
return
}
if !keepCapacity {
self = .native(NativeBuffer(bucketCount: 2))
return
}
if _fastPath(guaranteedNative) {
nativeRemoveAll()
return
}
switch self {
case .native:
nativeRemoveAll()
#if _runtime(_ObjC)
case .cocoa(let cocoaBuffer):
self = .native(NativeBuffer(minimumCapacity: cocoaBuffer.count))
#endif
}
}
@inlinable // FIXME(sil-serialize-all)
internal var count: Int {
if _fastPath(guaranteedNative) {
return asNative.count
}
switch self {
case .native:
return asNative.count
#if _runtime(_ObjC)
case .cocoa(let cocoaBuffer):
return cocoaBuffer.count
#endif
}
}
/// Returns an iterator over the elements.
///
/// - Complexity: O(1).
@inlinable // FIXME(sil-serialize-all)
@inline(__always)
internal func makeIterator() -> SetIterator<Element> {
switch self {
case .native(let buffer):
return ._native(
start: asNative.startIndex, end: asNative.endIndex, buffer: buffer)
#if _runtime(_ObjC)
case .cocoa(let cocoaBuffer):
return ._cocoa(cocoaBuffer)
#endif
}
}
}
@_fixed_layout // FIXME(sil-serialize-all)
@usableFromInline
internal struct _NativeSetIndex<Element>: Comparable {
@usableFromInline
internal var offset: Int
@inlinable // FIXME(sil-serialize-all)
internal init(offset: Int) {
self.offset = offset
}
}
extension _NativeSetIndex {
@inlinable // FIXME(sil-serialize-all)
internal static func < (
lhs: _NativeSetIndex<Element>,
rhs: _NativeSetIndex<Element>
) -> Bool {
return lhs.offset < rhs.offset
}
@inlinable // FIXME(sil-serialize-all)
internal static func <= (
lhs: _NativeSetIndex<Element>,
rhs: _NativeSetIndex<Element>
) -> Bool {
return lhs.offset <= rhs.offset
}
@inlinable // FIXME(sil-serialize-all)
internal static func > (
lhs: _NativeSetIndex<Element>,
rhs: _NativeSetIndex<Element>
) -> Bool {
return lhs.offset > rhs.offset
}
@inlinable // FIXME(sil-serialize-all)
internal static func >= (
lhs: _NativeSetIndex<Element>,
rhs: _NativeSetIndex<Element>
) -> Bool {
return lhs.offset >= rhs.offset
}
@inlinable // FIXME(sil-serialize-all)
internal static func == (
lhs: _NativeSetIndex<Element>,
rhs: _NativeSetIndex<Element>
) -> Bool {
return lhs.offset == rhs.offset
}
}
#if _runtime(_ObjC)
@_fixed_layout // FIXME(sil-serialize-all)
@usableFromInline
internal struct _CocoaSetIndex: Comparable {
// Assumption: we rely on NSDictionary.getObjects when being
// repeatedly called on the same NSDictionary, returning items in the same
// order every time.
// Similarly, the same assumption holds for NSSet.allObjects.
/// A reference to the NSSet, which owns members in `allObjects`,
/// or `allKeys`, for NSSet and NSDictionary respectively.
@usableFromInline // FIXME(sil-serialize-all)
internal let cocoaSet: _NSSet
// FIXME: swift-3-indexing-model: try to remove the cocoa reference, but make
// sure that we have a safety check for accessing `allKeys`. Maybe move both
// into the dictionary/set itself.
/// An unowned array of keys.
@usableFromInline // FIXME(sil-serialize-all)
internal var allKeys: _HeapBuffer<Int, AnyObject>
/// Index into `allKeys`
@usableFromInline // FIXME(sil-serialize-all)
internal var currentKeyIndex: Int
@inlinable // FIXME(sil-serialize-all)
internal init(_ cocoaSet: _NSSet, startIndex: ()) {
self.cocoaSet = cocoaSet
self.allKeys = _stdlib_NSSet_allObjects(cocoaSet)
self.currentKeyIndex = 0
}
@inlinable // FIXME(sil-serialize-all)
internal init(_ cocoaSet: _NSSet, endIndex: ()) {
self.cocoaSet = cocoaSet
self.allKeys = _stdlib_NSSet_allObjects(cocoaSet)
self.currentKeyIndex = allKeys.value
}
@inlinable // FIXME(sil-serialize-all)
internal init(_ cocoaSet: _NSSet,
_ allKeys: _HeapBuffer<Int, AnyObject>,
_ currentKeyIndex: Int
) {
self.cocoaSet = cocoaSet
self.allKeys = allKeys
self.currentKeyIndex = currentKeyIndex
}
/// Returns the next consecutive value after `self`.
///
/// - Precondition: The next value is representable.
@inlinable // FIXME(sil-serialize-all)
internal func successor() -> _CocoaSetIndex {
// FIXME: swift-3-indexing-model: remove this method.
_precondition(
currentKeyIndex < allKeys.value, "Cannot increment endIndex")
return _CocoaSetIndex(cocoaSet, allKeys, currentKeyIndex + 1)
}
}
extension _CocoaSetIndex {
@inlinable // FIXME(sil-serialize-all)
internal static func < (
lhs: _CocoaSetIndex,
rhs: _CocoaSetIndex
) -> Bool {
return lhs.currentKeyIndex < rhs.currentKeyIndex
}
@inlinable // FIXME(sil-serialize-all)
internal static func <= (
lhs: _CocoaSetIndex,
rhs: _CocoaSetIndex
) -> Bool {
return lhs.currentKeyIndex <= rhs.currentKeyIndex
}
@inlinable // FIXME(sil-serialize-all)
internal static func > (
lhs: _CocoaSetIndex,
rhs: _CocoaSetIndex
) -> Bool {
return lhs.currentKeyIndex > rhs.currentKeyIndex
}
@inlinable // FIXME(sil-serialize-all)
internal static func >= (
lhs: _CocoaSetIndex,
rhs: _CocoaSetIndex
) -> Bool {
return lhs.currentKeyIndex >= rhs.currentKeyIndex
}
@inlinable // FIXME(sil-serialize-all)
internal static func == (
lhs: _CocoaSetIndex,
rhs: _CocoaSetIndex
) -> Bool {
return lhs.currentKeyIndex == rhs.currentKeyIndex
}
}
#endif
@_frozen // FIXME(sil-serialize-all)
@usableFromInline // FIXME(sil-serialize-all)
internal enum SetIndexRepresentation<Element: Hashable> {
@usableFromInline
typealias _Index = SetIndex<Element>
@usableFromInline
typealias _NativeIndex = _Index._NativeIndex
#if _runtime(_ObjC)
@usableFromInline
typealias _CocoaIndex = _Index._CocoaIndex
#endif
case _native(_NativeIndex)
#if _runtime(_ObjC)
case _cocoa(_CocoaIndex)
#endif
}
extension Set {
/// The position of an element in a set.
@_fixed_layout // FIXME(sil-serialize-all)
public struct Index: Comparable, Hashable {
// Index for native buffer is efficient. Index for bridged NSSet is
// not, because neither NSEnumerator nor fast enumeration support moving
// backwards. Even if they did, there is another issue: NSEnumerator does
// not support NSCopying, and fast enumeration does not document that it is
// safe to copy the state. So, we cannot implement Index that is a value
// type for bridged NSSet in terms of Cocoa enumeration facilities.
@usableFromInline
internal typealias _NativeIndex = _NativeSetIndex<Element>
#if _runtime(_ObjC)
@usableFromInline
internal typealias _CocoaIndex = _CocoaSetIndex
#endif
@inlinable // FIXME(sil-serialize-all)
internal init(_value: SetIndexRepresentation<Element>) {
self._value = _value
}
@usableFromInline // FIXME(sil-serialize-all)
internal var _value: SetIndexRepresentation<Element>
@inlinable // FIXME(sil-serialize-all)
internal static func _native(_ index: _NativeIndex) -> Index {
return SetIndex(_value: ._native(index))
}
#if _runtime(_ObjC)
@inlinable // FIXME(sil-serialize-all)
internal static func _cocoa(_ index: _CocoaIndex) -> Index {
return SetIndex(_value: ._cocoa(index))
}
#endif
@usableFromInline @_transparent
internal var _guaranteedNative: Bool {
return _canBeClass(Element.self) == 0
}
@usableFromInline @_transparent
internal var _nativeIndex: _NativeIndex {
switch _value {
case ._native(let nativeIndex):
return nativeIndex
#if _runtime(_ObjC)
case ._cocoa:
_sanityCheckFailure("internal error: does not contain a native index")
#endif
}
}
#if _runtime(_ObjC)
@usableFromInline @_transparent
internal var _cocoaIndex: _CocoaIndex {
switch _value {
case ._native:
_sanityCheckFailure("internal error: does not contain a Cocoa index")
case ._cocoa(let cocoaIndex):
return cocoaIndex
}
}
#endif
}
}
public typealias SetIndex<Element: Hashable> = Set<Element>.Index
extension Set.Index {
@inlinable // FIXME(sil-serialize-all)
public static func == (
lhs: Set<Element>.Index,
rhs: Set<Element>.Index
) -> Bool {
if _fastPath(lhs._guaranteedNative) {
return lhs._nativeIndex == rhs._nativeIndex
}
switch (lhs._value, rhs._value) {
case (._native(let lhsNative), ._native(let rhsNative)):
return lhsNative == rhsNative
#if _runtime(_ObjC)
case (._cocoa(let lhsCocoa), ._cocoa(let rhsCocoa)):
return lhsCocoa == rhsCocoa
default:
_preconditionFailure("Comparing indexes from different sets")
#endif
}
}
@inlinable // FIXME(sil-serialize-all)
public static func < (
lhs: Set<Element>.Index,
rhs: Set<Element>.Index
) -> Bool {
if _fastPath(lhs._guaranteedNative) {
return lhs._nativeIndex < rhs._nativeIndex
}
switch (lhs._value, rhs._value) {
case (._native(let lhsNative), ._native(let rhsNative)):
return lhsNative < rhsNative
#if _runtime(_ObjC)
case (._cocoa(let lhsCocoa), ._cocoa(let rhsCocoa)):
return lhsCocoa < rhsCocoa
default:
_preconditionFailure("Comparing indexes from different sets")
#endif
}
}
/// Hashes the essential components of this value by feeding them into the
/// given hasher.
///
/// - Parameter hasher: The hasher to use when combining the components
/// of this instance.
@inlinable
public func hash(into hasher: inout Hasher) {
#if _runtime(_ObjC)
if _fastPath(_guaranteedNative) {
hasher.combine(0 as UInt8)
hasher.combine(_nativeIndex.offset)
return
}
switch _value {
case ._native(let nativeIndex):
hasher.combine(0 as UInt8)
hasher.combine(nativeIndex.offset)
case ._cocoa(let cocoaIndex):
hasher.combine(1 as UInt8)
hasher.combine(cocoaIndex.currentKeyIndex)
}
#else
hasher.combine(_nativeIndex.offset)
#endif
}
}
#if _runtime(_ObjC)
@usableFromInline
final internal class _CocoaSetIterator: IteratorProtocol {
@usableFromInline
internal typealias Element = AnyObject
// Cocoa Set iterator has to be a class, otherwise we cannot
// guarantee that the fast enumeration struct is pinned to a certain memory
// location.
// This stored property should be stored at offset zero. There's code below
// relying on this.
internal var _fastEnumerationState: _SwiftNSFastEnumerationState =
_makeSwiftNSFastEnumerationState()
// This stored property should be stored right after `_fastEnumerationState`.
// There's code below relying on this.
internal var _fastEnumerationStackBuf = _CocoaFastEnumerationStackBuf()
internal let cocoaSet: _NSSet
internal var _fastEnumerationStatePtr:
UnsafeMutablePointer<_SwiftNSFastEnumerationState> {
return _getUnsafePointerToStoredProperties(self).assumingMemoryBound(
to: _SwiftNSFastEnumerationState.self)
}
internal var _fastEnumerationStackBufPtr:
UnsafeMutablePointer<_CocoaFastEnumerationStackBuf> {
return UnsafeMutableRawPointer(_fastEnumerationStatePtr + 1)
.assumingMemoryBound(to: _CocoaFastEnumerationStackBuf.self)
}
// These members have to be word-sized integers, they cannot be limited to
// Int8 just because our storage holds 16 elements: fast enumeration is
// allowed to return inner pointers to the container, which can be much
// larger.
internal var itemIndex: Int = 0
internal var itemCount: Int = 0
internal init(_ cocoaSet: _NSSet) {
self.cocoaSet = cocoaSet
}
@usableFromInline
internal func next() -> Element? {
if itemIndex < 0 {
return nil
}
let cocoaSet = self.cocoaSet
if itemIndex == itemCount {
let stackBufCount = _fastEnumerationStackBuf.count
// We can't use `withUnsafeMutablePointer` here to get pointers to
// properties, because doing so might introduce a writeback storage, but
// fast enumeration relies on the pointer identity of the enumeration
// state struct.
itemCount = cocoaSet.countByEnumerating(
with: _fastEnumerationStatePtr,
objects: UnsafeMutableRawPointer(_fastEnumerationStackBufPtr)
.assumingMemoryBound(to: AnyObject.self),
count: stackBufCount)
if itemCount == 0 {
itemIndex = -1
return nil
}
itemIndex = 0
}
let itemsPtrUP =
UnsafeMutableRawPointer(_fastEnumerationState.itemsPtr!)
.assumingMemoryBound(to: AnyObject.self)
let itemsPtr = _UnmanagedAnyObjectArray(itemsPtrUP)
let key: AnyObject = itemsPtr[itemIndex]
itemIndex += 1
return key
}
}
#endif
@usableFromInline
@_frozen // FIXME(sil-serialize-all)
internal enum SetIteratorRepresentation<Element: Hashable> {
@usableFromInline
internal typealias _Iterator = SetIterator<Element>
@usableFromInline
internal typealias _NativeBuffer = _NativeSetBuffer<Element>
@usableFromInline
internal typealias _NativeIndex = _Iterator._NativeIndex
// For native buffer, we keep two indices to keep track of the iteration
// progress and the buffer owner to make the buffer non-uniquely
// referenced.
//
// Iterator is iterating over a frozen view of the collection
// state, so it should keep its own reference to the buffer.
case _native(
start: _NativeIndex, end: _NativeIndex, buffer: _NativeBuffer)
#if _runtime(_ObjC)
case _cocoa(_CocoaSetIterator)
#endif
}
/// An iterator over the members of a `Set<Element>`.
@_fixed_layout // FIXME(sil-serialize-all)
public struct SetIterator<Element: Hashable>: IteratorProtocol {
// Set has a separate IteratorProtocol and Index because of efficiency
// and implementability reasons.
//
// Index for native buffer is efficient. Index for bridged NSSet is
// not.
//
// Even though fast enumeration is not suitable for implementing
// Index, which is multi-pass, it is suitable for implementing a
// IteratorProtocol, which is being consumed as iteration proceeds.
@usableFromInline
internal typealias _NativeBuffer = _NativeSetBuffer<Element>
@usableFromInline
internal typealias _NativeIndex = _NativeSetIndex<Element>
@usableFromInline
internal var _state: SetIteratorRepresentation<Element>
@inlinable // FIXME(sil-serialize-all)
internal init(_state: SetIteratorRepresentation<Element>) {
self._state = _state
}
@inlinable // FIXME(sil-serialize-all)
internal static func _native(
start: _NativeIndex, end: _NativeIndex, buffer: _NativeBuffer
) -> SetIterator {
return SetIterator(
_state: ._native(start: start, end: end, buffer: buffer))
}
#if _runtime(_ObjC)
@usableFromInline
internal static func _cocoa(_ buffer: _CocoaSetBuffer) -> SetIterator {
let iterator = _CocoaSetIterator(buffer.cocoaSet)
return SetIterator(_state: ._cocoa(iterator))
}
#endif
@usableFromInline @_transparent
internal var _guaranteedNative: Bool {
return _canBeClass(Element.self) == 0
}
@inlinable // FIXME(sil-serialize-all)
internal mutating func _nativeNext() -> Element? {
switch _state {
case ._native(let startIndex, let endIndex, let buffer):
if startIndex == endIndex {
return nil
}
let result = buffer.assertingGet(at: startIndex)
_state =
._native(start: buffer.index(after: startIndex), end: endIndex, buffer: buffer)
return result
#if _runtime(_ObjC)
case ._cocoa:
_sanityCheckFailure("internal error: not backed by NSSet")
#endif
}
}
/// Advances to the next element and returns it, or `nil` if no next element
/// exists.
///
/// Once `nil` has been returned, all subsequent calls return `nil`.
@inlinable // FIXME(sil-serialize-all)
@inline(__always)
public mutating func next() -> Element? {
if _fastPath(_guaranteedNative) {
return _nativeNext()
}
switch _state {
case ._native:
return _nativeNext()
#if _runtime(_ObjC)
case ._cocoa(let cocoaIterator):
if let anyObjectElement = cocoaIterator.next() {
return _forceBridgeFromObjectiveC(anyObjectElement, Element.self)
}
return nil
#endif
}
}
}
extension SetIterator: CustomReflectable {
/// A mirror that reflects the iterator.
public var customMirror: Mirror {
return Mirror(
self,
children: EmptyCollection<(label: String?, value: Any)>())
}
}
extension Set: CustomReflectable {
/// A mirror that reflects the set.
public var customMirror: Mirror {
let style = Mirror.DisplayStyle.`set`
return Mirror(self, unlabeledChildren: self, displayStyle: style)
}
}
/// Initializes a `Set` from unique members.
///
/// Using a builder can be faster than inserting members into an empty
/// `Set`.
@_fixed_layout // FIXME(sil-serialize-all)
public struct _SetBuilder<Element: Hashable> {
@usableFromInline // FIXME(sil-serialize-all)
internal var _result: Set<Element>
@usableFromInline // FIXME(sil-serialize-all)
internal var _nativeBuffer: _NativeSetBuffer<Element>
@usableFromInline // FIXME(sil-serialize-all)
internal let _requestedCount: Int
@usableFromInline // FIXME(sil-serialize-all)
internal var _actualCount: Int
@inlinable // FIXME(sil-serialize-all)
public init(count: Int) {
_result = Set<Element>(minimumCapacity: count)
_nativeBuffer = _result._variantBuffer.asNative
_requestedCount = count
_actualCount = 0
}
@inlinable // FIXME(sil-serialize-all)
public mutating func add(member: Element) {
_nativeBuffer.unsafeAddNew(key: member)
_actualCount += 1
}
@inlinable // FIXME(sil-serialize-all)
public mutating func take() -> Set<Element> {
_precondition(_actualCount >= 0,
"Cannot take the result twice")
_precondition(_actualCount == _requestedCount,
"The number of members added does not match the promised count")
// Finish building the `Set`.
_nativeBuffer.count = _requestedCount
// Prevent taking the result twice.
_actualCount = -1
return _result
}
}
extension Set {
/// Removes and returns the first element of the set.
///
/// Because a set is not an ordered collection, the "first" element may not
/// be the first element that was added to the set.
///
/// - Returns: A member of the set. If the set is empty, returns `nil`.
@inlinable
public mutating func popFirst() -> Element? {
guard !isEmpty else { return nil }
return remove(at: startIndex)
}
/// The total number of elements that the set can contain without
/// allocating new storage.
@inlinable // FIXME(sil-serialize-all)
public var capacity: Int {
return _variantBuffer.capacity
}
/// Reserves enough space to store the specified number of elements.
///
/// If you are adding a known number of elements to a set, use this
/// method to avoid multiple reallocations. This method ensures that the
/// set has unique, mutable, contiguous storage, with space allocated
/// for at least the requested number of elements.
///
/// Calling the `reserveCapacity(_:)` method on a set with bridged
/// storage triggers a copy to contiguous storage even if the existing
/// storage has room to store `minimumCapacity` elements.
///
/// - Parameter minimumCapacity: The requested number of elements to
/// store.
@inlinable // FIXME(sil-serialize-all)
public mutating func reserveCapacity(_ minimumCapacity: Int) {
_variantBuffer.reserveCapacity(minimumCapacity)
_sanityCheck(self.capacity >= minimumCapacity)
}
}
//===--- Bridging ---------------------------------------------------------===//
#if _runtime(_ObjC)
extension Set {
@inlinable // FIXME(sil-serialize-all)
public func _bridgeToObjectiveCImpl() -> _NSSetCore {
switch _variantBuffer {
case _VariantSetBuffer.native(let buffer):
return buffer.bridged()
case _VariantSetBuffer.cocoa(let cocoaBuffer):
return cocoaBuffer.cocoaSet
}
}
/// Returns the native Dictionary hidden inside this NSDictionary;
/// returns nil otherwise.
public static func _bridgeFromObjectiveCAdoptingNativeStorageOf(
_ s: AnyObject
) -> Set<Element>? {
// Try all three NSSet impls that we currently provide.
if let deferredBuffer = s as? _SwiftDeferredNSSet<Element> {
return Set(_nativeBuffer: deferredBuffer.nativeBuffer)
}
if let nativeStorage = s as? _HashableTypedNativeSetStorage<Element> {
return Set(_nativeBuffer:
_NativeSetBuffer(_storage: nativeStorage))
}
if s === _RawNativeSetStorage.empty {
return Set()
}
// FIXME: what if `s` is native storage, but for different key/value type?
return nil
}
}
#endif
| apache-2.0 | 857b700d5c4f9e3d4d56d15a4bf84f98 | 31.745441 | 115 | 0.670045 | 4.188395 | false | false | false | false |
cristianodp/Aulas-IOS | Aula4/ListaItens/ListaItens/Controll/ItemController.swift | 1 | 2419 | //
// ItemController.swift
// ListaItens
//
// Created by Cristiano Diniz Pinto on 01/06/17.
// Copyright © 2017 Cristiano Diniz Pinto. All rights reserved.
//
import Foundation
import Alamofire
import SwiftyJSON
class ItemController {
static func getLista(callback:@escaping ([Item]?,Error?)->Void){
Alamofire.request("http://glasslu.com.br/ws/item-buscar.php").responseJSON(completionHandler: { (responseData) in
if let obj = responseData.result.value{
print(obj)
let json = JSON(obj)
let arrayJson = json.arrayValue
var itens = [Item]()
arrayJson.forEach({ (itemJson) in
let it = Item.init(data: itemJson)
itens.append(it)
_ = DBUtils.shareInstance.insert(data: it)
})
_ = DBUtils.shareInstance.getItens()
callback(itens,nil)
}
})
}
/* static func getList(callback:@escaping ([Cidade]?,Error?) -> Void)
{
let reachability = Reachability()!
if reachability.isReachable == false {
callback(nil,exceptionErros.notConnected)
return
}
let urlString = AppServices.BUSCA_CIDADES_WS + estId.description
Alamofire.request(urlString).responseJSON(completionHandler: { (responseData) in
if let object = responseData.result.value{
let json = JSON(object)
print(json)
if retornoValido(json) {
if let cidades = self.getDataFormResponse(reponseJson: json){
callback(cidades,nil)
}else{
callback(nil,exceptionErros.NoDataFound)
}
}else{
callback(nil,exceptionErros.erroRetornoWebService("Erro de comunicação com webservice"))
}
}else{
callback(nil,responseData.result.error)
}
})
}*/
}
| apache-2.0 | f7fb525badd5e7fa9fe69b652d04d05b | 28.108434 | 121 | 0.464404 | 5.392857 | false | false | false | false |
huonw/swift | benchmark/single-source/CString.swift | 3 | 3750 | //===--- CString.swift ----------------------------------------------------===//
//
// 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 TestsUtils
#if os(Linux)
import Glibc
#else
import Darwin
#endif
public let CString = [
BenchmarkInfo(name: "CStringLongAscii", runFunction: run_CStringLongAscii, tags: [.validation, .api, .String, .bridging]),
BenchmarkInfo(name: "CStringLongNonAscii", runFunction: run_CStringLongNonAscii, tags: [.validation, .api, .String, .bridging]),
BenchmarkInfo(name: "CStringShortAscii", runFunction: run_CStringShortAscii, tags: [.validation, .api, .String, .bridging]),
BenchmarkInfo(name: "StringWithCString", runFunction: run_StringWithCString, tags: [.validation, .api, .String, .bridging]),
]
let ascii = "Swift is a multi-paradigm, compiled programming language created for iOS, OS X, watchOS, tvOS and Linux development by Apple Inc. Swift is designed to work with Apple's Cocoa and Cocoa Touch frameworks and the large body of existing Objective-C code written for Apple products. Swift is intended to be more resilient to erroneous code (\"safer\") than Objective-C and also more concise. It is built with the LLVM compiler framework included in Xcode 6 and later and uses the Objective-C runtime, which allows C, Objective-C, C++ and Swift code to run within a single program."
let japanese = "日本語(にほんご、にっぽんご)は、主に日本国内や日本人同士の間で使われている言語である。"
@inline(never)
public func run_StringWithCString(_ N: Int) {
let str = String(repeating: "x", count: 100 * (1 << 16))
for _ in 0 ..< N {
str.withCString { blackHole($0) }
}
}
@inline(never)
public func run_CStringLongAscii(_ N: Int) {
var res = 0
for _ in 1...N*500 {
// static string to c -> from c to String -> implicit conversion
res &= strlen(ascii.withCString(String.init(cString:)))
}
CheckResults(res == 0)
}
@inline(never)
public func run_CStringLongNonAscii(_ N: Int) {
var res = 0
for _ in 1...N*500 {
res &= strlen(japanese.withCString(String.init(cString:)))
}
CheckResults(res == 0)
}
let input = ["-237392", "293715", "126809", "333779", "-362824", "144198",
"-394973", "-163669", "-7236", "376965", "-400783", "-118670",
"454728", "-38915", "136285", "-448481", "-499684", "68298",
"382671", "105432", "-38385", "39422", "-267849", "-439886",
"292690", "87017", "404692", "27692", "486408", "336482",
"-67850", "56414", "-340902", "-391782", "414778", "-494338",
"-413017", "-377452", "-300681", "170194", "428941", "-291665",
"89331", "329496", "-364449", "272843", "-10688", "142542",
"-417439", "167337", "96598", "-264104", "-186029", "98480",
"-316727", "483808", "300149", "-405877", "-98938", "283685",
"-247856", "-46975", "346060", "160085",]
let reference = 517492
@inline(never)
public func run_CStringShortAscii(_ N: Int) {
func DoOneIter(_ arr: [String]) -> Int {
var r = 0
for n in arr {
r += Int(atoi(n))
}
if r < 0 {
r = -r
}
return r
}
var res = Int.max
for _ in 1...100*N {
let strings = input.map {
$0.withCString(String.init(cString:))
}
res = res & DoOneIter(strings)
}
CheckResults(res == reference)
}
| apache-2.0 | 9122d3dfca28ff48450c82b3c04fa431 | 38.376344 | 589 | 0.618788 | 3.448211 | false | false | false | false |
derekcoder/SwiftDevHints | SwiftDevHints/Classes/DictionaryExtensions.swift | 2 | 10197 | //
// DictionaryExtensions.swift
// SwiftDevHints
//
// Created by ZHOU DENGFENG on 1/8/17.
// Copyright © 2017 ZHOU DENGFENG DEREK. All rights reserved.
//
import Foundation
public enum Type: Int {
case number
case bool
case string
case array
case dictionary
case null
case unknown
public static func type(forValue value: Any) -> Type {
switch value {
case let number as NSNumber:
if number.isBool {
return .bool
} else {
return .number
}
case _ as String: return .string
case _ as NSNull: return .null
case _ as [Any]: return .array
case _ as [String: Any]: return .dictionary
default: return .unknown
}
}
}
public extension Dictionary where Key: CustomStringConvertible {
/// Returns the NSNumber value for the given key.
///
/// - Parameter key: The key to find in the dictionary
/// - Returns: The NSNumber value for `key` if `key` in the dictionary, otherwise, `0`.
func numberValue(forKey key: Key) -> NSNumber {
guard let value = self[key] else { return NSNumber(value: 0.0) }
let type = Type.type(forValue: value)
switch type {
case .bool: return (value as! NSNumber)
case .number: return (value as! NSNumber)
case .string:
let decimal = NSDecimalNumber(string: value as? String)
if decimal == NSDecimalNumber.notANumber {
return NSDecimalNumber.zero
}
return decimal
default: return false
}
}
func number(forKey key: Key) -> NSNumber? {
guard let value = self[key] else { return nil }
let type = Type.type(forValue: value)
switch type {
case .bool: return (value as! NSNumber)
case .number: return (value as! NSNumber)
case .string:
let decimal = NSDecimalNumber(string: value as? String)
if decimal == NSDecimalNumber.notANumber {
return NSDecimalNumber.zero
}
return decimal
default: return nil
}
}
/// Returns the String value for the given key.
///
/// - Parameter key: The key to find in the dictionary.
/// - Returns: The String value for key if key in the dictionary, otherwise, "".
func stringValue(forKey key: Key) -> String {
guard let value = self[key] else { return "" }
let type = Type.type(forValue: value)
switch type {
case .string: return (value as! String)
case .bool: return numberValue(forKey: key).stringValue
case .number: return numberValue(forKey: key).stringValue
default: return ""
}
}
func string(forKey key: Key) -> String? {
guard let value = self[key] else { return nil }
let type = Type.type(forValue: value)
switch type {
case .string: return (value as! String)
case .bool: return numberValue(forKey: key).stringValue
case .number: return numberValue(forKey: key).stringValue
default: return nil
}
}
/// Returns the Bool value for the given key.
///
/// If type of the object for the given key is String and its value is "true" or "yes" or "1", this method will return `true`.
///
/// - Parameter key: The key to find in the dictionary.
/// - Returns: The Bool value for `key` if `key` in the dictionary, otherwise, `false`.
func boolValue(forKey key: Key) -> Bool {
guard let value = self[key] else { return false }
let type = Type.type(forValue: value)
switch type {
case .bool: return numberValue(forKey: key).boolValue
case .number: return numberValue(forKey: key).boolValue
case .string:
return ["true", "yes", "1"].contains() { string in
return (value as! String).caseInsensitiveCompare(string) == .orderedSame
}
default: return false
}
}
func bool(forKey key: Key) -> Bool? {
guard let value = self[key] else { return nil }
let type = Type.type(forValue: value)
switch type {
case .bool: return numberValue(forKey: key).boolValue
case .number: return numberValue(forKey: key).boolValue
case .string:
return ["true", "yes", "1"].contains() { string in
return (value as! String).caseInsensitiveCompare(string) == .orderedSame
}
default: return nil
}
}
/// Return the Int value for the given key.
///
/// - Parameter key: The key to find in the dictionary.
/// - Returns: The Int value for `key`.
func intValue(forKey key: Key) -> Int {
return numberValue(forKey: key).intValue
}
func int(forKey key: Key) -> Int? {
return number(forKey: key)?.intValue
}
/// Return the UInt value for the given key.
///
/// - Parameter key: The key to find in the dictionary.
/// - Returns: The UInt value for `key`.
func uIntValue(forKey key: Key) -> UInt {
return numberValue(forKey: key).uintValue
}
func uInt(forKey key: Key) -> UInt? {
return number(forKey: key)?.uintValue
}
/// Return the Int8 value for the given key.
///
/// - Parameter key: The key to find in the dictionary.
/// - Returns: The Int8 value for `key`.
func int8Value(forKey key: Key) -> Int8 {
return numberValue(forKey: key).int8Value
}
func int8(forKey key: Key) -> Int8? {
return number(forKey: key)?.int8Value
}
/// Return the UInt8 value for the given key.
///
/// - Parameter key: The key to find in the dictionary.
/// - Returns: The UInt8 value for `key`.
func uInt8Value(forKey key: Key) -> UInt8 {
return numberValue(forKey: key).uint8Value
}
func uInt8(forKey key: Key) -> UInt8? {
return number(forKey: key)?.uint8Value
}
/// Return the Int16 value for the given key.
///
/// - Parameter key: The key to find in the dictionary.
/// - Returns: The Int16 value for `key`.
func int16Value(forKey key: Key) -> Int16 {
return numberValue(forKey: key).int16Value
}
func int16(forKey key: Key) -> Int16? {
return number(forKey: key)?.int16Value
}
/// Return the UInt16 value for the given key.
///
/// - Parameter key: The key to find in the dictionary.
/// - Returns: The UInt16 value for `key`.
func uInt16Value(forKey key: Key) -> UInt16 {
return numberValue(forKey: key).uint16Value
}
func uInt16(forKey key: Key) -> UInt16? {
return number(forKey: key)?.uint16Value
}
/// Return the Int32 value for the given key.
///
/// - Parameter key: The key to find in the dictionary.
/// - Returns: The Int32 value for `key`.
func int32Value(forKey key: Key) -> Int32 {
return numberValue(forKey: key).int32Value
}
func int32(forKey key: Key) -> Int32? {
return number(forKey: key)?.int32Value
}
/// Return the UInt32 value for the given key.
///
/// - Parameter key: The key to find in the dictionary.
/// - Returns: The UInt32 value for `key`.
func uInt32Value(forKey key: Key) -> UInt32 {
return numberValue(forKey: key).uint32Value
}
func uInt32(forKey key: Key) -> UInt32? {
return number(forKey: key)?.uint32Value
}
/// Return the Int64 value for the given key.
///
/// - Parameter key: The key to find in the dictionary.
/// - Returns: The Int64 value for `key`.
func int64Value(forKey key: Key) -> Int64 {
return numberValue(forKey: key).int64Value
}
func int64(forKey key: Key) -> Int64? {
return number(forKey: key)?.int64Value
}
/// Return the UInt64 value for the given key.
///
/// - Parameter key: The key to find in the dictionary.
/// - Returns: The UInt64 value for `key`.
func uInt64Value(forKey key: Key) -> UInt64 {
return numberValue(forKey: key).uint64Value
}
func uInt64(forKey key: Key) -> UInt64? {
return number(forKey: key)?.uint64Value
}
/// Return the Double value for the given key.
///
/// - Parameter key: The key to find in the dictionary.
/// - Returns: The Double value for `key`.
func doubleValue(forKey key: Key) -> Double {
return numberValue(forKey: key).doubleValue
}
func double(forKey key: Key) -> Double? {
return number(forKey: key)?.doubleValue
}
/// Return the Float value for the given key.
///
/// - Parameter key: The key to find in the dictionary.
/// - Returns: The Float value for `key`.
func floatValue(forKey key: Key) -> Float {
return numberValue(forKey: key).floatValue
}
func float(forKey key: Key) -> Float? {
return number(forKey: key)?.floatValue
}
func dict(forKey key: Key) -> Dictionary? {
return self[key] as? Dictionary
}
func dictArray(forKey key: Key) -> [Dictionary]? {
return self[key] as? [Dictionary]
}
}
public extension Dictionary {
subscript(jsonDict key: Key) -> [String: Any]? {
get { return self[key] as? [String: Any] }
set { self[key] = newValue as? Value }
}
subscript(string key: Key) -> String? {
get { return self[key] as? String }
set { self[key] = newValue as? Value }
}
subscript(int key: Key) -> Int? {
get { return self[key] as? Int }
set { self[key] = newValue as? Value }
}
}
public extension Dictionary {
func mapKeys<T>(_ transform: ((Key) throws -> T)) rethrows -> Dictionary<T, Value> {
var newDict: [T: Value] = [:]
for (key, value) in self {
let newKey = try transform(key)
newDict[newKey] = value
}
return newDict
}
}
| mit | 05a627586a979a6c3e8084d52c0a7665 | 29.89697 | 130 | 0.577089 | 4.237739 | false | false | false | false |
chrisjmendez/swift-exercises | Basic/REST/HTTPRequests/HTTPRequests/ViewController.swift | 1 | 4318 | //
// ViewController.swift
// HTTPRequests
//
// Created by tommy trojan on 5/17/15.
// Copyright (c) 2015 Chris Mendez. All rights reserved.
//
import UIKit
//https://github.com/daltoniam/swiftHTTP
import SwiftHTTP
class ViewController: UIViewController {
let logo:String = "https://pbs.twimg.com/profile_images/596047686089871360/TqOLJ2cz.png"
@IBAction func onGETClicked(sender: AnyObject) {
basicGET()
}
@IBAction func onPOSTClicked(sender: AnyObject) {
basicPOST()
}
@IBAction func onDownloadClicked(sender: AnyObject) {
basicDownload()
}
@IBAction func onPOSTAPIClicked(sender: AnyObject) {
basicPOSTAPI()
}
func basicGET(){
var request = HTTPTask()
request.GET("http://i.ng.ht/visitors/trace",
parameters: nil,
success: {(response: HTTPResponse) -> Void in
if let data = response.responseObject as? NSData {
let str = NSString(data: data, encoding: NSUTF8StringEncoding)
println("response: \(str)") //prints the HTML of the page
}
},
failure: {(error: NSError, response: HTTPResponse?) -> Void in
println("got an error: \(error)")
})
}
func basicPOST(){
//we have to add the explicit type, else the wrong type is inferred. See the vluxe.io article for more info.
let params: Dictionary<String,AnyObject> = ["param": "param1", "array": ["first array element","second","third"], "num": 23, "dict": ["someKey": "someVal"]]
var request = HTTPTask()
request.POST("http://i.ng.ht/visitors/trace", parameters: params, success: {(response: HTTPResponse) in
if let data = response.responseObject as? NSData {
let str = NSString(data: data, encoding: NSUTF8StringEncoding)
println("response: \(str)")
}
}, failure: {(error: NSError, response: HTTPResponse?) -> Void in
println("got an error: \(error)")
})
}
func basicDownload(){
var request = HTTPTask()
let downloadTask = request.download(logo,
parameters: nil,
progress: {(complete: Double) in
println("percent complete: \(complete)")
},
success: {(response: HTTPResponse) in
println("download finished!")
if let url = response.responseObject as? NSURL {
//we MUST copy the file from its temp location to a permanent location.
if let path = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true).first as? String {
if let fileName = response.suggestedFilename {
if let newPath = NSURL(fileURLWithPath: "\(path)/\(fileName)") {
let fileManager = NSFileManager.defaultManager()
fileManager.removeItemAtURL(newPath, error: nil)
fileManager.moveItemAtURL(url, toURL: newPath, error:nil)
}
}
}
}
},
failure: {(error: NSError, response: HTTPResponse?) -> Void in
println("error: \(error.localizedDescription)")
return //also notify app of failure as needed
})
}
func basicPOSTAPI(){
var request = HTTPTask()
request.baseURL = "http://i.ng.ht/"
request.POST("/visitors/trace", parameters: ["key": "updatedVale"], success: {(response: HTTPResponse) in
println("Got data from \(response.text)")
},
failure: {(error: NSError, response: HTTPResponse?) -> Void in
println("error: \(error.localizedDescription)")
return //also notify app of failure as needed
})
}
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.
}
}
| mit | ad2be05406b2656170f52578c81bb7fb | 35.905983 | 164 | 0.561371 | 4.940503 | false | false | false | false |
burntheroad/RoundDropMenu | Pod/Classes/Views/RoundDropMenu.swift | 1 | 11820 | //
// RoundDropMenuView.swift
// Round-Drop Menu
//
// Created by Arthur Myronenko on 15.03.15.
// Copyright (c) 2015 Arthur Myronenko. All rights reserved.
//
import UIKit
/// A `RoundDropMenu` displays list of items in form of circular views that are
/// scrolled by horizontal axis.
public class RoundDropMenu: UIView {
// MARK: - Delegate and Data Source
/// The object that acts as the delegate of the menu.
public var delegate: RoundDropMenuDelegate!
/// The object that acts as the data source of the menu.
public var dataSource: RoundDropMenuDataSource! { didSet { reloadData() } }
// MARK: - Menu Appearance
/// Color of oval in center of menu.
public var color: UIColor = UIColor(red: 1.0, green: 1.0, blue: 22.0/255.0, alpha: 1.0)
/// Padding of the oval in center of menu.
public var offset: CGFloat = 80
// MARK: Drop Appearance
/// Radius of the drop in center of menu. Default is 40.0.
public var maxDropRadius: CGFloat = 40.0
/// Radius of the drop on the edge of menu. Default is 20.0
public var minDropRadius: CGFloat = 20.0
/// Radius that is used to calculate dropView's position and scale.
private var outlineRadius: CGFloat! { return frame.width / 2 + frame.width / 4 }
// MARK: - Menu Properties
/// An array of `DropView` objects loaded from the data source.
/// Should be changed only by `reloadData().`
private var dropViews = [DropView]()
/// Index of the currently selected drop. Can be nil only if there are no drops in menu.
private var selectedDropIndex: Int? {
didSet {
if let dropView = selectedDropView {
if (oldValue != nil) && (dropViews[oldValue!] !== nil) {
dropViews[oldValue!].highlited = false
}
dropView.highlited = true
}
delegate?.roundDropMenu(self, didSelectDropWithIndex: selectedDropIndex!)
}
}
/// Horizontal scroll position of menu.
private var scrollPosition: CGFloat = 0.0 {
didSet {
if scrollPosition < 0.0 {
scrollPosition = 0.0
} else if scrollPosition > maxDropsScrollPosition {
scrollPosition = maxDropsScrollPosition
}
if scrollPosition != oldValue {
selectedDropIndex = Int(round(scrollPosition / dropWidthWithOffset))
}
}
}
/// Stores location of pan gesture start.
private var panStart: CGFloat = 0.0
// MARK: Computed Properties
/// Maximum width of dropView with offset.
private var dropWidthWithOffset: CGFloat { return (maxDropRadius * 2 + 20) }
/// Maximum content width of the menu.
private var maxDropsScrollPosition: CGFloat {
let dropsCount = dataSource.numberOfDropsInRoundDropMenu(self)
return dropsCount == 0 ? 0 : CGFloat(dropsCount - 1) * dropWidthWithOffset
}
/// Returns a `DropView` object that is currently selected in the menu.
private var selectedDropView: DropView? {
guard let index = selectedDropIndex else { return nil }
return dropViews[index]
}
}
// MARK: - View Lifecycle
extension RoundDropMenu {
override public func didMoveToSuperview() {
super.didMoveToSuperview()
let panGesture = UIPanGestureRecognizer(target: self, action: Selector("dropsScroll:"))
addGestureRecognizer(panGesture)
}
override public func layoutSubviews() {
super.layoutSubviews()
translateSelectedDropToCenter()
}
override public func drawRect(rect: CGRect) {
let ovalRect = CGRect(
x: rect.origin.x,
y: rect.origin.y + 20,
width: rect.width,
height: rect.height * 2)
let ovalPath = UIBezierPath(ovalInRect: CGRectInset(ovalRect, 20, offset))
ovalPath.addClip()
color.setFill()
UIRectFill(bounds)
super.drawRect(rect)
}
}
// MARK: - Managing Data
extension RoundDropMenu {
/**
Reloads all dropViews from data source.
*/
public func reloadData() {
dropViews = []
let dropsCount = dataSource.numberOfDropsInRoundDropMenu(self)
for i in 0..<dropsCount {
let dropView = dataSource.roundDropMenu(self, dropViewForIndex: i)
dropView.frame.origin = CGPoint(x: CGFloat(i) * dropWidthWithOffset, y: 0)
addSubview(dropView)
dropViews.append(dropView)
}
if selectedDropIndex == nil || selectedDropIndex >= dropViews.count {
selectedDropIndex = 0
}
}
}
// MARK: - DropViews Repositioning
extension RoundDropMenu {
/**
Translates all drops by provided x-axis offset.
- parameter offset: X-axis offset to move drops.
- parameter animated: Boolean value that indicates if translating should be performed animated.
*/
private func moveDropsWithOffset(offset: CGFloat, animated: Bool = false) {
for dropView in self.dropViews {
let newPosition = getDropPosition(dropView, afterApplyingOffset: offset)
if animated {
animateDropMove(dropView, newPosition: newPosition)
} else {
dropView.center = newPosition
}
if dropIsVisible(dropView) {
resizeDropView(dropView, animated: animated)
}
}
}
/**
Calculates offset needed to translate `selectedDropView` to the center
of the menu and applies `moveDropsWithOffset(_:, animated:).`
*/
private func translateSelectedDropToCenter() {
if let centerDrop = selectedDropView {
let scrollOffset = bounds.midX - centerDrop.center.x
moveDropsWithOffset(scrollOffset, animated: true)
if let index = selectedDropIndex {
self.scrollPosition = CGFloat(index) * self.dropWidthWithOffset
}
}
}
/**
Indicates if provided `dropView`'s bounds is in the menu's frame.
- parameter dropView: `DropView` object to check.
- returns: `true` if `dropView`'s frame located fully in the menu, `false` otherwise.
*/
private func dropIsVisible(dropView: DropView) -> Bool {
return !(dropView.center.x > frame.width + maxDropRadius || dropView.center.x < -maxDropRadius)
}
/**
Animates `dropView`'s transition to new position.
- parameter dropView: `DropView` objects to move.
- parameter newPosition: New position.
*/
// swiftlint:disable function_body_length
private func animateDropMove(dropView: DropView, newPosition: CGPoint) {
let midPointX1 = dropView.center.x + (newPosition.x - dropView.center.x) / 3
let midPoint1 = CGPoint(x: midPointX1, y: getYOnCircleForX(midPointX1))
let midPointX2 = dropView.center.x + 2 * (newPosition.x - dropView.center.x) / 3
let midPoint2 = CGPoint(x: midPointX2, y: getYOnCircleForX(midPointX2))
let dropPath = UIBezierPath()
dropPath.moveToPoint(dropView.center)
dropPath.addCurveToPoint(newPosition, controlPoint1: midPoint1, controlPoint2: midPoint2)
let midViewFrame1 = getDropViewFrameAtPosition(midPoint1)
let midViewFrame2 = getDropViewFrameAtPosition(midPoint2)
let endViewFrame = getDropViewFrameAtPosition(newPosition)
let midLabelPoint1 = CGPoint(
x: midViewFrame1.width / 2,
y: -1 - dropView.label.frame.height / 2)
let midLabelPoint2 = CGPoint(
x: midViewFrame2.width / 2,
y: -1 - dropView.label.frame.height / 2)
let endLabelPoint = CGPoint(
x: endViewFrame.width / 2,
y: -1 - dropView.label.frame.height / 2)
let labelPath = UIBezierPath()
labelPath.moveToPoint(
CGPoint(x: dropView.frame.width / 2, y: -1 - dropView.label.frame.height / 2))
labelPath.addCurveToPoint(endLabelPoint,
controlPoint1: midLabelPoint1,
controlPoint2: midLabelPoint2)
let animation = CAKeyframeAnimation(keyPath: "position")
animation.path = dropPath.CGPath
animation.removedOnCompletion = true
animation.fillMode = kCAFillModeForwards
animation.duration = 0.1
animation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut)
dropView.layer.addAnimation(animation, forKey: nil)
animation.path = labelPath.CGPath
dropView.label.layer.addAnimation(animation, forKey: nil)
dropView.center = newPosition
}
// swiftlint:enable function_body_length
/**
Calculates new position of `dropView` after translating translating it along x-axis by `offset`.
- parameter dropView: `DropView` object to move.
- parameter offset: Offset by x-axis.
- returns: New `dropView` position.
*/
private func getDropPosition(dropView: DropView, afterApplyingOffset offset: CGFloat) -> CGPoint {
var result = dropView.center
result.x += offset
if dropIsVisible(dropView) {
result.y = getYOnCircleForX(result.x)
}
return result
}
/**
Calculates y-coordinate based on provided x-coordinate, `outlineRadius` and `maxDropRadius`.
- parameter xValue: Provided value of x-axis.
- returns: y-coordinate.
*/
private func getYOnCircleForX(xValue: CGFloat) -> CGFloat {
func sqr(num: CGFloat) -> CGFloat { return num * num }
// (x-menuCenter.x)^2 + (y-(dropRadius + outlineRadius))^2=outlineRadius^2
if xValue <= bounds.midX - outlineRadius || xValue >= bounds.midX + outlineRadius {
return maxDropRadius + outlineRadius
}
return -sqrt(sqr(outlineRadius) - sqr(xValue - bounds.midX)) + maxDropRadius + outlineRadius
}
/**
Scales provided `dropView` accordingly to it's position.
- parameter dropView: `DropView` object to scale.
- parameter animated: Boolean value that indicates if scaling should be performed animated.
*/
private func resizeDropView(dropView: DropView, animated: Bool = false) {
let newDropFrame = getDropViewFrameAtPosition(dropView.center)
if animated {
animateDropResize(dropView, newSize: newDropFrame)
} else {
dropView.frame = newDropFrame
}
}
/**
Calculates frame for `DropView` object accordingly to provided `position`.
- parameter position: `CGPoint` struct to calculate new frame.
- returns: Frame for `DropView` object on `position`.
*/
private func getDropViewFrameAtPosition(position: CGPoint) -> CGRect {
let offsetRelativeToCenter = abs(position.x - bounds.midX)
let scaleValue = 1 - offsetRelativeToCenter / bounds.midX
let dropScale = 2 * ((maxDropRadius - minDropRadius) * scaleValue + minDropRadius)
return CGRect(
x: position.x - dropScale/2,
y: position.y - dropScale/2,
width: dropScale,
height: dropScale)
}
/**
Animate provided `dropView`'s layer resizing to `newSize`.
- parameter dropView: `DropView` object to resize.
- parameter newSize: Needed size.
*/
private func animateDropResize(dropView: DropView, newSize: CGRect) {
var s = newSize
s.origin = CGPointZero
let animation = CABasicAnimation(keyPath: "bounds")
animation.fromValue = NSValue(&dropView.bounds, withObjCType: "CGRect")
animation.toValue = NSValue(&s, withObjCType: "CGRect")
animation.duration = 0.1
animation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut)
dropView.layer.addAnimation(animation, forKey: "resizeAnimation")
dropView.frame = newSize
}
}
// MARK: - Gestures
extension RoundDropMenu {
@objc private func dropsScroll(gestureRecognizer: UIPanGestureRecognizer) {
if gestureRecognizer.state == .Began {
panStart = gestureRecognizer.locationInView(self).x
}
if gestureRecognizer.state == UIGestureRecognizerState.Changed {
let scrollOffset = (gestureRecognizer.locationInView(self).x - panStart) / 2
panStart = gestureRecognizer.locationInView(self).x
scrollPosition -= scrollOffset
moveDropsWithOffset(scrollOffset)
}
if gestureRecognizer.state == .Ended {
translateSelectedDropToCenter()
}
}
}
| mit | 25d37edf5589b7c0269e250a60c073a4 | 32.109244 | 100 | 0.686802 | 4.215407 | false | false | false | false |
TarangKhanna/Inspirator | WorkoutMotivation/TimelineViewController.swift | 2 | 41013 | //
// TimeLineViewController.swift
// AutomatePortal
//
// Created by Tarang Khanna on 2/28/15. Design inspiration from AppDesign Vault.
// Copyright (c) 2015 Thacked. All rights reserved.
//
//MAKE SURE USER IS LOGGED IN
import Foundation
import UIKit
import MapKit
import Parse
import Social
import MessageUI
//import Spring
// fix lag
class TimelineViewController : UIViewController, UITableViewDelegate, UITableViewDataSource, UITextFieldDelegate, floatMenuDelegate, MFMailComposeViewControllerDelegate {
@IBOutlet var postData: MKTextField!
@IBOutlet var tableView : SBGestureTableView!
@IBOutlet weak var menuBarButton: UIBarButtonItem!
var newIndexPathRow: Int? = nil
@IBOutlet var menuItem : UIBarButtonItem!
@IBOutlet var statusLabel: UILabel!
var selectedParseObjectId = String()
var selectedParseObject:PFObject?
var ParseObjectId : [String] = [""]
//var selectedObject = PFObject()
var containsImage = [Bool]() // for loading images and making sure index is not out of bounds
var votedArray = [String]()
var activityIndicator = UIActivityIndicatorView()
var indexPathStore = NSIndexPath()
var parseObject:PFObject?
var currLocation: CLLocationCoordinate2D?
let locationManager = CLLocationManager()
//var transitionOperator = TransitionOperator()
var messages = [String]()
var createdAt = [Int]()
var score = [Int]()
var userArray: [String] = []
var imageFiles = [PFFile]()
var selectedName: String = "default"
var selectedScore: String = "default"
var selectedToReportMessage: String = "default"
var selectedToReportObject:PFObject?
var selectedAbout: String = "default"
var startTime: CFAbsoluteTime!
var timeAtPress: NSDate!
var elapsedTime: NSDate!
var duration : Int = 0
var profileImageFile = PFFile()
var profileImageFiles = [PFFile]()
var previousUser = String()
var circleColors = [UIColor.MKColor.LightBlue, UIColor.MKColor.Grey, UIColor.MKColor.LightGreen, UIColor.MKColor.Amber, UIColor.MKColor.DeepOrange]
var voteObject = [PFObject]()
//var potentialVoteCounter : Int? = object["count"]
var selectedFirstPost = String()
// gesture tableview configs
let checkIcon = FAKIonIcons.ios7ArrowUpIconWithSize(30)
let closeIcon = FAKIonIcons.ios7ArrowUpIconWithSize(30) // downvote swipe left
let composeIcon = FAKIonIcons.ios7ArrowDownIconWithSize(30)
let clockIcon = FAKIonIcons.ios7ArrowDownIconWithSize(30) // upvote -swipe right
let greenColor = UIColor(red: 85.0/255, green: 213.0/255, blue: 80.0/255, alpha: 1)
let redColor = UIColor(red: 213.0/255, green: 70.0/255, blue: 70.0/255, alpha: 1)
let yellowColor = UIColor(red: 236.0/255, green: 223.0/255, blue: 60.0/255, alpha: 1)
let brownColor = UIColor(red: 182.0/255, green: 127.0/255, blue: 78.0/255, alpha: 1)
var removeCellBlock: ((SBGestureTableView, SBGestureTableViewCell) -> Void)!
var groupToQuery : String? = "general"
var currentUser : String? = nil
var currentUserId : String? = nil
override func viewWillAppear(animated: Bool) {
self.navigationController!.navigationBar.hidden = false
self.navigationController?.setNavigationBarHidden(false, animated: true)
if let currentUser = PFUser.currentUser()!.username {
currentUserId = PFUser.currentUser()?.objectId
} else {
performSegueWithIdentifier("signIn", sender: self)
}
}
@IBAction func upVote(sender: AnyObject) {
//let buttonRow = sender.tag
if let buttonRow = sender.tag { // or from removeBlock
var votedBy = voteObject[buttonRow]["votedBy"] as! [String]
if !(votedBy.contains(currentUserId!)) {
var scoreParse = voteObject[buttonRow]["score"]! as? Int
scoreParse = scoreParse! + 1
voteObject[buttonRow].setObject(NSNumber(integer: scoreParse!), forKey: "score")
print(currentUserId)
votedBy.append(currentUserId!)
voteObject[buttonRow]["upVote"] = true
voteObject[buttonRow]["votedBy"] = votedBy
voteObject[buttonRow].saveInBackgroundWithBlock {
(success: Bool, error: NSError?) -> Void in
if (success) {
// update cell locally atleast and maybe not call self.retrieve
//
//self.tableView.reloadSections(NSIndexSet(index: 0), withRowAnimation: UITableViewRowAnimation.Fade)
self.retrieve()
} else {
print("Couldn't Vote!")
SCLAlertView().showWarning("Error Voting", subTitle: "Check Your Internet Connection.")
}
}
} else { // already voted -- add to retrieve also
// var indexPath = NSIndexPath(forRow: buttonRow, inSection: 0)
let upVoted : Bool = (voteObject[buttonRow]["upVote"]! as? Bool)!
if !upVoted { // if prev was downvote
// then upvote by +2
var scoreParse = voteObject[buttonRow]["score"]! as? Int
scoreParse = scoreParse! + 2
voteObject[buttonRow].setObject(NSNumber(integer: scoreParse!), forKey: "score")
//votedBy.append(currentUserId!)
voteObject[buttonRow]["upVote"] = true
//voteObject[buttonRow]["votedBy"] = votedBy
voteObject[buttonRow].saveInBackgroundWithBlock {
(success: Bool, error: NSError?) -> Void in
if (success) {
self.retrieve()
} else {
print("Couldn't Vote!")
SCLAlertView().showWarning("Error Voting", subTitle: "Check Your Internet Connection.")
}
}
}
print("Already Voted")
// self.tableView.reloadRowsAtIndexPaths([indexPathStore], withRowAnimation: UITableViewRowAnimation.Top)
}
} else {
var votedBy = voteObject[newIndexPathRow!]["votedBy"] as! [String]
if !(votedBy.contains(currentUserId!)) {
var scoreParse = voteObject[newIndexPathRow!]["score"]! as? Int
scoreParse = scoreParse! + 1
voteObject[newIndexPathRow!].setObject(NSNumber(integer: scoreParse!), forKey: "score")
print(currentUserId)
votedBy.append(currentUserId!)
voteObject[newIndexPathRow!]["upVote"] = true
voteObject[newIndexPathRow!]["votedBy"] = votedBy
voteObject[newIndexPathRow!].saveInBackgroundWithBlock {
(success: Bool, error: NSError?) -> Void in
if (success) {
// update cell locally atleast and maybe not call self.retrieve
//
//self.tableView.reloadSections(NSIndexSet(index: 0), withRowAnimation: UITableViewRowAnimation.Fade)
self.retrieve()
} else {
print("Couldn't Vote!")
SCLAlertView().showWarning("Error Voting", subTitle: "Check Your Internet Connection.")
}
}
} else { // already voted -- add to retrieve also
// var indexPath = NSIndexPath(forRow: buttonRow, inSection: 0)
let upVoted : Bool = (voteObject[newIndexPathRow!]["upVote"]! as? Bool)!
if !upVoted { // if prev was downvote
// then upvote by +2
var scoreParse = voteObject[newIndexPathRow!]["score"]! as? Int
scoreParse = scoreParse! + 2
voteObject[newIndexPathRow!].setObject(NSNumber(integer: scoreParse!), forKey: "score")
//votedBy.append(currentUserId!)
voteObject[newIndexPathRow!]["upVote"] = true
//voteObject[buttonRow]["votedBy"] = votedBy
voteObject[newIndexPathRow!].saveInBackgroundWithBlock {
(success: Bool, error: NSError?) -> Void in
if (success) {
self.retrieve()
} else {
print("Couldn't Vote!")
SCLAlertView().showWarning("Error Voting", subTitle: "Check Your Internet Connection.")
}
}
}
print("Already Voted")
// self.tableView.reloadRowsAtIndexPaths([indexPathStore], withRowAnimation: UITableViewRowAnimation.Top)
}
}
}
@IBAction func downVote(sender: AnyObject) {
if let buttonRow = sender.tag {
var votedBy = voteObject[buttonRow]["votedBy"] as! [String]
if !(votedBy.contains(currentUserId!)) {
var scoreParse = voteObject[buttonRow]["score"]! as? Int
scoreParse = scoreParse! - 1
voteObject[buttonRow].setObject(NSNumber(integer: scoreParse!), forKey: "score")
votedBy.append(currentUserId!)
voteObject[buttonRow]["upVote"] = false
voteObject[buttonRow]["votedBy"] = votedBy
voteObject[buttonRow].saveInBackgroundWithBlock {
(success: Bool, error: NSError?) -> Void in
if (success) {
self.retrieve()
} else {
print("Couldn't Vote!")
SCLAlertView().showWarning("Error Voting", subTitle: "Check Your Internet Connection.")
}
}
} else { // already voted -- add to retrieve also
let upVoted : Bool = (voteObject[buttonRow]["upVote"]! as? Bool)!
if upVoted {
// then downvote by -2
var scoreParse = voteObject[buttonRow]["score"]! as? Int
scoreParse = scoreParse! - 2
voteObject[buttonRow].setObject(NSNumber(integer: scoreParse!), forKey: "score")
//votedBy.append(currentUserId!)
voteObject[buttonRow]["upVote"] = false
//voteObject[buttonRow]["votedBy"] = votedBy
voteObject[buttonRow].saveInBackgroundWithBlock {
(success: Bool, error: NSError?) -> Void in
if (success) {
self.retrieve()
} else {
print("Couldn't Vote!")
SCLAlertView().showWarning("Error Voting", subTitle: "Check Your Internet Connection.")
}
}
}
print("Already Voted")
}
} else {
var votedBy = voteObject[newIndexPathRow!]["votedBy"] as! [String]
if !(votedBy.contains(currentUserId!)) {
var scoreParse = voteObject[newIndexPathRow!]["score"]! as? Int
scoreParse = scoreParse! - 1
voteObject[newIndexPathRow!].setObject(NSNumber(integer: scoreParse!), forKey: "score")
votedBy.append(currentUserId!)
voteObject[newIndexPathRow!]["upVote"] = false
voteObject[newIndexPathRow!]["votedBy"] = votedBy
voteObject[newIndexPathRow!].saveInBackgroundWithBlock {
(success: Bool, error: NSError?) -> Void in
if (success) {
self.retrieve()
} else {
print("Couldn't Vote!")
SCLAlertView().showWarning("Error Voting", subTitle: "Check Your Internet Connection.")
}
}
} else { // already voted -- add to retrieve also
let upVoted : Bool = (voteObject[newIndexPathRow!]["upVote"]! as? Bool)!
if upVoted {
// then downvote by -2
var scoreParse = voteObject[newIndexPathRow!]["score"]! as? Int
scoreParse = scoreParse! - 2
voteObject[newIndexPathRow!].setObject(NSNumber(integer: scoreParse!), forKey: "score")
//votedBy.append(currentUserId!)
voteObject[newIndexPathRow!]["upVote"] = false
//voteObject[buttonRow]["votedBy"] = votedBy
voteObject[newIndexPathRow!].saveInBackgroundWithBlock {
(success: Bool, error: NSError?) -> Void in
if (success) {
self.retrieve()
} else {
print("Couldn't Vote!")
SCLAlertView().showWarning("Error Voting", subTitle: "Check Your Internet Connection.")
}
}
}
print("Already Voted")
}
}
}
override func viewDidLoad() {
super.viewDidLoad()
self.automaticallyAdjustsScrollViewInsets = false
if self.revealViewController() != nil {
menuBarButton.target = self.revealViewController()
menuBarButton.action = "revealToggle:"
self.view.addGestureRecognizer(self.revealViewController().panGestureRecognizer())
}
// postData.layer.borderColor = UIColor.clearColor().CGColor
// postData.placeholder = "Placeholder"
// postData.tintColor = UIColor.grayColor()
//self.navigationController?.navigationBar.barStyle = UIBarStyle.BlackTranslucent
self.view.backgroundColor = UIColor(patternImage: UIImage(named: "loginBG.png")!)
self.navigationController?.navigationBar.setBackgroundImage(UIImage(named: "loginBG.png"), forBarMetrics: UIBarMetrics.Compact)
self.navigationController?.navigationBar.tintColor = UIColor.redColor()
self.navigationController?.navigationBar.titleTextAttributes = [NSForegroundColorAttributeName: UIColor.redColor()]
//self.view.backgroundColor = UIColor(red: 90/255.0, green: 187/255.0, blue: 181/255.0, alpha: 1.0) //teal
//self.navigationController?.hidesBarsOnSwipe = true
//self.navigationController?.navigationBar.backgroundColor = UIColor(red: 90/255.0, green: 187/255.0, blue: 181/255.0, alpha: 1.0) //teal
tableView.backgroundColor = UIColor.clearColor()
tableView.delegate = self
tableView.dataSource = self
tableView.estimatedRowHeight = 100.0;
tableView.rowHeight = UITableViewAutomaticDimension;
tableView.separatorStyle = UITableViewCellSeparatorStyle.None
_ = PFUser.currentUser()?.username
// set this image at time of signup / signin
_ = UIImage()
// var queryUser = PFUser.query() as PFQuery?
// queryUser!.findObjectsInBackgroundWithBlock {
// (users: [AnyObject]?, error: NSError?) -> Void in
// if error == nil {
// if let users = users as? [PFObject] {
// for user in users {
// var user2:PFUser = user as! PFUser
// if user2.username == self.currentUser
// {
// var userPhotoFile = user2["ProfilePicture"] as! PFFile
// userPhotoFile.getDataInBackgroundWithBlock { (data, error) -> Void in
//
// if let downloadedImage = UIImage(data: data!) {
// userPhoto = downloadedImage
// actionButton.imageArray = ["fb-icon.png","twitter-icon.png","google-icon.png","downloadedImage"]
// }
//
// }
// }
// }
// }
// }
// }
SwiftSpinner.show("Connecting to Group...")
retrieve()
self.tableView.addPullToRefresh({ [weak self] in
// refresh code
SwiftSpinner.show("Refreshing")
self!.retrieve()
//self?.retrieve()
//self?.tableView.reloadData()
self?.tableView.stopPullToRefresh()
})
setupIcons()
tableView.didMoveCellFromIndexPathToIndexPathBlock = {(fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) -> Void in
//self.objects.exchangeObjectAtIndex(toIndexPath.row, withObjectAtIndex: fromIndexPath.row)
}
removeCellBlock = {(tableView: SBGestureTableView, cell: SBGestureTableViewCell) -> Void in
let indexPath = tableView.indexPathForCell(cell)
print(Int(cell.center.x))
if Int(cell.center.x) > 0 { // upvote
print(indexPath?.row)
self.newIndexPathRow = indexPath?.row
self.upVote(self)
} else if Int(cell.center.x) < 0 {
print(indexPath?.row)
print("fjb ejkbf")
self.newIndexPathRow = indexPath?.row
self.downVote(self)
}
UIView.animateWithDuration(0.2 * cell.percentageOffsetFromCenter(), animations: { () -> Void in
//cell.center = CGPointMake(cell.frame.size.width/2 + (cell.frame.origin.x > 0 ? -bounce : bounce), cell.center.y)
cell.leftSideView.iconImageView.alpha = 0
cell.rightSideView.iconImageView.alpha = 0
}, completion: {(done) -> Void in
UIView.animateWithDuration(0.2/2, animations: { () -> Void in
cell.center = CGPointMake(cell.frame.size.width/2, cell.center.y)
}, completion: {(done) -> Void in
cell.leftSideView.removeFromSuperview()
cell.rightSideView.removeFromSuperview()
//completion?()
})
})
print(cell.leftSideView)
}
}
func setupIcons() {
checkIcon.addAttribute(NSForegroundColorAttributeName, value: UIColor.whiteColor())
closeIcon.addAttribute(NSForegroundColorAttributeName, value: UIColor.whiteColor())
composeIcon.addAttribute(NSForegroundColorAttributeName, value: UIColor.whiteColor())
clockIcon.addAttribute(NSForegroundColorAttributeName, value: UIColor.whiteColor())
}
func retrieve() {
var currentProfileUser = ""
if let query = PFQuery(className: "Person") as PFQuery? { //querying parse for user data
query.orderByDescending("createdAt")
query.limit = 25
query.findObjectsInBackgroundWithBlock({ (objects, error) -> Void in
if error != nil {
self.statusLabel.text = "No Internet. Try refreshing."
}
self.containsImage.removeAll(keepCapacity: false)
self.imageFiles.removeAll(keepCapacity: false)
self.messages.removeAll(keepCapacity: false)
self.profileImageFiles.removeAll(keepCapacity: false)
self.userArray.removeAll(keepCapacity: false)
self.score.removeAll(keepCapacity: false)
self.createdAt.removeAll(keepCapacity: false)
self.voteObject.removeAll(keepCapacity: false)
self.votedArray.removeAll(keepCapacity: false)
self.ParseObjectId.removeAll(keepCapacity: false)
if let objects = objects as? [PFObject] {
for object in objects {
if self.groupToQuery! == object["group"] as? String || self.groupToQuery == "general" { // here we set the group
if let imageFile42 = object["imageFile"] as? PFFile {
self.imageFiles.append(imageFile42)
self.containsImage.append(true)
} else {
self.imageFiles.append(PFFile())
self.containsImage.append(false)
}
currentProfileUser = object["username"] as! String
// append profile pics here and optimise
self.voteObject.append(object)
self.ParseObjectId.append((object.objectId! as String?)!)
self.messages.append(object["text"] as! String)
self.userArray.append(currentProfileUser)
//self.score.append(object["score"] as! Int)
let elapsedTime = CFAbsoluteTimeGetCurrent() - (object["startTime"] as! CFAbsoluteTime)
self.duration = Int(elapsedTime/60)
self.createdAt.append(self.duration)
}
}
}
//dispatch_async(dispatch_get_main_queue()) {
self.delay(0.3) {
let queryUser2 = PFUser.query() as PFQuery?
queryUser2!.findObjectsInBackgroundWithBlock {
(users: [AnyObject]?, error: NSError?) -> Void in
if error == nil {
for user42 in self.userArray {
// Do something with the found users
if let users = users as? [PFObject] {
for user in users {
let user2:PFUser = user as! PFUser
//println(user42)
if user2.username == user42 {
self.profileImageFiles.append(user2["ProfilePicture"] as! PFFile)
}
}
}
}
} else {
print("Error: \(error!) \(error!.userInfo)")
}
}
//}
}
self.delay(6) {
print(self.profileImageFiles.count)
print("3io4h3jnk4jkn")
print(self.userArray.count)
// dispatch_async(dispatch_get_main_queue()) {
if self.profileImageFiles.count == self.userArray.count{
SwiftSpinner.hide()
self.tableView.reloadData()
} else {
self.retrieve()
}
}
})
//if profileImageFiles.count == userArray.count {
// }
//}
}
//dispatch_async(dispatch_get_main_queue()) {
//self.loadProfileImages()
//}
}
func delay(delay:Double, closure:()->()) {
dispatch_after(
dispatch_time(
DISPATCH_TIME_NOW,
Int64(delay * Double(NSEC_PER_SEC))
),
dispatch_get_main_queue(), closure)
}
//
// func locationManager(manager: CLLocationManager!, didUpdateLocations locations: [AnyObject]!) {
// locationManager.stopUpdatingLocation()
// if(locations.count > 0){
// let location = locations[0] as! CLLocation
// currLocation = location.coordinate
// } else {
// println("error")
// }
// }
// func locationManager(manager: CLLocationManager!, didFailWithError error: NSError!) {
// println(error)
// }
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
//tableView.reloadData()
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return userArray.count
}
func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
return true
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
if containsImage[indexPath.row] {
print("PIC")
indexPathStore = indexPath
var cell = tableView.dequeueReusableCellWithIdentifier("TimelineCellPhoto") as? SBGestureTableViewCell
if cell == nil {
cell = SBGestureTableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: "TimelineCellPhoto")
}
let size = CGSizeMake(30, 30)
let profileImage42 = self.profileImageFiles[indexPath.row]
profileImage42.getDataInBackgroundWithBlock { (data, error) -> Void in
if !(error != nil) {
if let downloadedImage = UIImage(data: data!) {
cell!.profileImageView?.image = downloadedImage
}
}
}
// got profile pic
// Profile Tap
cell!.profileImageView.tag = indexPath.row
let tapGestureRecognizer = UITapGestureRecognizer(target:self, action:Selector("profileImageTapped:"))
cell!.profileImageView.userInteractionEnabled = true
cell!.profileImageView.addGestureRecognizer(tapGestureRecognizer)
cell!.firstLeftAction = SBGestureTableViewCellAction(icon: checkIcon.imageWithSize(size), color: greenColor, fraction: 0.3, didTriggerBlock: removeCellBlock)
//cell.secondLeftAction = SBGestureTableViewCellAction(icon: closeIcon.imageWithSize(size), color: greenColor, fraction: 0.6, didTriggerBlock: removeCellBlock)
cell!.firstRightAction = SBGestureTableViewCellAction(icon: composeIcon.imageWithSize(size), color: redColor, fraction: 0.3, didTriggerBlock: removeCellBlock)
//cell.secondRightAction = SBGestureTableViewCellAction(icon: clockIcon.imageWithSize(size), color: redColor, fraction: 0.6, didTriggerBlock: removeCellBlock)
cell!.backgroundColor = UIColor.clearColor()
// cell.downVoteBtn.tag = indexPath.row
//
// cell.downVoteBtn.addTarget(self, action: "downVote:", forControlEvents: UIControlEvents.TouchUpInside)
// cell.upVoteBtn.tag = indexPath.row
//
// cell.upVoteBtn.addTarget(self, action: "upVote:", forControlEvents: UIControlEvents.TouchUpInside)
var name = self.userArray[indexPath.row]
name.replaceRange(name.startIndex...name.startIndex, with: String(name[name.startIndex]).capitalizedString)
cell!.nameLabel.text = name
cell!.nameLabel.textColor = UIColor.whiteColor()
cell!.postLabel?.text = "\u{200B}\(self.messages[indexPath.row])"
cell!.postLabel?.textColor = UIColor.whiteColor()
cell!.typeImageView.image = UIImage(named: "timeline-photo")
let index = indexPath.row % circleColors.count
cell!.rippleLayerColor = circleColors[index]
let seconds = self.createdAt[indexPath.row]*60
let temp = seconds
var timeAgo = (seconds/60) // + " m ago"
var ending = " min"
var setAlready = false
if timeAgo >= 60 { // min now
timeAgo = (temp / 3600)
ending = " hrs"
if timeAgo >= 24 {
timeAgo = timeAgo / 24
ending = " days"
if timeAgo == 1 {
setAlready = true
cell!.dateLabel.text = "yesterday"
}
}
}
if !setAlready {
cell!.dateLabel.text = String(timeAgo) + ending
}
cell!.dateLabel.text = String(timeAgo) + ending
cell!.dateLabel.textColor = UIColor.MKColor.Grey
cell!.scoreLabel.textColor = UIColor.whiteColor()
cell!.scoreLabel.text = "[" + String(self.score[indexPath.row]) + "]"
let image42 = self.imageFiles[indexPath.row]
image42.getDataInBackgroundWithBlock { (data, error) -> Void in
if !(error != nil) {
if let downloadedImage2 = UIImage(data: data!) {
//self.tableView.insertRowsAtIndexPaths(0, withRowAnimation: UITableViewRowAnimation.Bottom)
cell!.photoImageView?.image = downloadedImage2
}
}
}
return cell!
} else {
print("TEXT")
indexPathStore = indexPath
var cell = tableView.dequeueReusableCellWithIdentifier("TimelineCell") as? SBGestureTableViewCell
if cell == nil {
cell = SBGestureTableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: "TimelineCell")
}
let size = CGSizeMake(30, 30)
print(profileImageFiles.count)
let profileImage42 = self.profileImageFiles[indexPath.row]
profileImage42.getDataInBackgroundWithBlock { (data, error) -> Void in
if (error == nil) {
if let downloadedImage = UIImage(data: data!) {
cell!.profileImageView?.image = downloadedImage
}
}
}
let longPressGestureRecognizer = UILongPressGestureRecognizer(target: self, action: Selector("longPressOptions:"))
cell?.userInteractionEnabled = true
cell?.addGestureRecognizer(longPressGestureRecognizer)
cell!.profileImageView.tag = indexPath.row
let tapGestureRecognizer = UITapGestureRecognizer(target:self, action:Selector("profileImageTapped:"))
cell!.profileImageView.userInteractionEnabled = true
cell!.profileImageView.addGestureRecognizer(tapGestureRecognizer)
cell!.firstLeftAction = SBGestureTableViewCellAction(icon: checkIcon.imageWithSize(size), color: greenColor, fraction: 0.3, didTriggerBlock: removeCellBlock)
cell!.secondLeftAction = SBGestureTableViewCellAction(icon: closeIcon.imageWithSize(size), color: greenColor, fraction: 0.6, didTriggerBlock: removeCellBlock)
cell!.firstRightAction = SBGestureTableViewCellAction(icon: composeIcon.imageWithSize(size), color: redColor, fraction: 0.3, didTriggerBlock: removeCellBlock)
cell!.secondRightAction = SBGestureTableViewCellAction(icon: clockIcon.imageWithSize(size), color: redColor, fraction: 0.6, didTriggerBlock: removeCellBlock)
cell!.backgroundColor = UIColor.clearColor()
cell!.downVoteButton.tag = indexPath.row
cell!.downVoteButton.addTarget(self, action: "downVote:", forControlEvents: UIControlEvents.TouchUpInside)
cell!.upvoteButton.tag = indexPath.row
cell!.upvoteButton.addTarget(self, action: "upVote:", forControlEvents: UIControlEvents.TouchUpInside)
let index = indexPath.row % circleColors.count
cell!.rippleLayerColor = circleColors[index]
//self.tableView.insertRowsAtIndexPaths(0, withRowAnimation: UITableViewRowAnimation.Bottom)
cell!.typeImageView.image = UIImage(named: "timeline-chat")
//cell.profileImageView.image = UIImage(named: "profile-pic-1")
var name = self.userArray[indexPath.row]
name.replaceRange(name.startIndex...name.startIndex, with: String(name[name.startIndex]).capitalizedString)
cell!.nameLabel.text = name
cell!.nameLabel.textColor = UIColor.whiteColor()
cell!.postLabel?.text = self.messages[indexPath.row]
cell!.postLabel?.textColor = UIColor.whiteColor()
let seconds = Double(self.createdAt[indexPath.row]*60)
let temp = seconds
var timeAgo = (seconds/60) // + " m ago"
var ending = " min"
var setAlready = false
if timeAgo >= 60 { // min now
timeAgo = (temp / 3600)
ending = " hrs"
if timeAgo >= 24.0 {
timeAgo = timeAgo / 24
ending = " days"
if timeAgo > 1.3 {
setAlready = true
cell!.dateLabel.text = "yesterday"
} else {
}
}
}
if !setAlready {
cell!.dateLabel.text = String(stringInterpolationSegment: Int(timeAgo)) + ending
}
cell!.dateLabel.textColor = UIColor.whiteColor()
cell!.scoreLabel.textColor = UIColor.whiteColor()
cell!.scoreLabel.text = "[" + String(self.score[indexPath.row]) + "]"
return cell!
}
}
func longPressOptions(recognizer: UILongPressGestureRecognizer) {
if (recognizer.state == UIGestureRecognizerState.Ended) {
let cellIndex = recognizer.view!.tag
selectedToReportObject = voteObject[cellIndex]
selectedToReportMessage = messages[cellIndex]
let alert = SCLAlertView()
alert.addButton("Report") {
let mailComposeViewController = self.configuredMailComposeViewController()
if MFMailComposeViewController.canSendMail() {
self.presentViewController(mailComposeViewController, animated: true, completion: nil)
} else {
self.showSendMailErrorAlert()
}
}
alert.addButton("Delete") {
}
alert.showEdit("Yes?", subTitle:"Choose:", closeButtonTitle: "Cancel")
}
else if (recognizer.state == UIGestureRecognizerState.Began) {
//Do Whatever You want on Began of Gesture
}
}
// MAIL
func configuredMailComposeViewController() -> MFMailComposeViewController {
let mailComposerVC = MFMailComposeViewController()
mailComposerVC.mailComposeDelegate = self
mailComposerVC.setToRecipients(["[email protected]"])
mailComposerVC.setSubject("Reporting for Inspirator")
let body = String(stringInterpolationSegment: selectedToReportObject) + "\r\n" + "Problem:"
mailComposerVC.setMessageBody(body, isHTML: false)
return mailComposerVC
}
func showSendMailErrorAlert() {
let sendMailErrorAlert = UIAlertView(title: "Could Not Send Email", message: "Your device could not send e-mail. Please check e-mail configuration and try again.", delegate: self, cancelButtonTitle: "OK")
sendMailErrorAlert.show()
}
func mailComposeController(controller: MFMailComposeViewController, didFinishWithResult result: MFMailComposeResult, error: NSError?) {
controller.dismissViewControllerAnimated(true, completion: nil)
}
// FINISH MAIL
func profileImageTapped(recognizer: UITapGestureRecognizer) {
let imageIndex = recognizer.view!.tag
selectedName = userArray[imageIndex]
selectedScore = String(score[imageIndex])
selectedParseObject = voteObject[imageIndex]
performSegueWithIdentifier("profileView", sender: self)
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
self.tableView.deselectRowAtIndexPath(indexPath, animated: true)
selectedName = userArray[indexPath.row]
selectedScore = String(score[indexPath.row])
selectedParseObject = voteObject[indexPath.row]
selectedFirstPost = messages[indexPath.row]
if let myObject = ParseObjectId[indexPath.row] as String? {
selectedParseObjectId = myObject
}
//let destinationVC = profileVC()
//destinationVC.name = selectedName
performSegueWithIdentifier("showComments", sender: self)
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject!) {
var recipients2 = [String]()
if (segue.identifier == "profileView") { //pass data to VC
let svc = (segue.destinationViewController as! UINavigationController).topViewController as! profileVC
print(selectedName)
svc.name = selectedName
svc.canChange = false
svc.score = selectedScore
svc.show = true
//svc.profileObject =
} else if (segue.identifier == "posting") {
let svc = (segue.destinationViewController as! UINavigationController).topViewController as! postingViewController
svc.passedGroup = groupToQuery!
} else if (segue.identifier == "showComments") { // get notified if you see comment section
let currentUserId = PFUser.currentUser()?.objectId
if var recipients = selectedParseObject!["recipients"] as? [String] { //added to receiver array, real notification on comment adding in commentsVC
if !(recipients.contains(currentUserId!)) {
print(PFUser.currentUser()?.objectId)
recipients.append(currentUserId!)
selectedParseObject!["recipients"] = recipients
recipients2 = recipients
// This will save both myPost and myComment
selectedParseObject!.saveInBackgroundWithBlock {
(success: Bool, error: NSError?) -> Void in
if (success) {
// update cell locally atleast and maybe not call self.retrieve
} else {
print("Couldn't subscribe!")
SCLAlertView().showWarning("Error Commenting", subTitle: "Check Your Internet Connection.")
}
}
}
} else {
selectedParseObject!["recipients"] = [String]()
var recipients3 = selectedParseObject!["recipients"] as? [String]
recipients3?.append(currentUserId!)
recipients2 = recipients3!
selectedParseObject!["recipients"] = recipients2
selectedParseObject!.saveInBackgroundWithBlock {
(success: Bool, error: NSError?) -> Void in
if (success) {
} else {
print("Couldn't Vote!")
SCLAlertView().showWarning("Error Commenting", subTitle: "Check Your Internet Connection.")
}
}
}
let svc = (segue.destinationViewController as! UINavigationController).topViewController as! CommentsVC // nav controller in between
if let parseID = selectedParseObjectId as String?{
svc.name = selectedName
svc.firstPost = selectedFirstPost
svc.objectIDPost = parseID
svc.recipients = recipients2
print(recipients2)
}
}
}
func textView(textView: UITextView!, shouldInteractWithURL URL: NSURL!, inRange characterRange: NSRange) -> Bool {
print("Link Selected!")
return true
}
}
| apache-2.0 | 9130f29adec5d5256a9ab480a86cc32d | 47.939141 | 213 | 0.54817 | 5.510009 | false | false | false | false |
emrecaliskan/ECDropDownList | ECDropDownList/ViewController.swift | 1 | 1613 | //
// ViewController.swift
// ECDropDownList
//
// Created by Emre Caliskan on 2015-03-23.
// Copyright (c) 2015 pictago. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
var items = [ECListItem]()
for var index = 0; index<10; index++ {
let item = ECListItem(text: "Item \(index)") { () -> () in
NSLog("Did Tap Item \(index)")
}
items.append(item)
}
let item1 = ECListItem(text: "Item 1") { () -> () in
NSLog("Did Tap Item 1")
}
let item2 = ECListItem(text: "Item 2") { () -> () in
NSLog("Did Tap Item 2")
}
let item3 = ECListItem(text: "Item 3") { () -> () in
NSLog("Did Tap Item 3")
}
let item4 = ECListItem(text: "Item 4") { () -> () in
NSLog("Did Tap Item 4")
}
let item5 = ECListItem(text: "Item 5") { () -> () in
NSLog("Did Tap Item 5")
}
let menu = ECListMenu(items: [item1, item2, item3, item4, item5])
let menuView = ECListMenuView(frame: CGRectMake(0, 40, self.view.bounds.width, self.view.bounds.height), listMenu: menu)
self.view.addSubview(menuView)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| mit | 1d626d999d1ead961cb13c5f25e8e982 | 26.338983 | 128 | 0.524489 | 4.042607 | false | false | false | false |
ruslanskorb/CoreStore | CoreStoreDemo/CoreStoreDemo/Fetching and Querying Demo/QueryingResultsViewController.swift | 1 | 2244 | //
// QueryingResultsViewController.swift
// CoreStoreDemo
//
// Created by John Rommel Estropia on 2015/06/17.
// Copyright © 2018 John Rommel Estropia. All rights reserved.
//
import UIKit
class QueryingResultsViewController: UITableViewController {
// MARK: Public
func set(value: Any?, title: String) {
switch value {
case (let array as [Any])?:
self.values = array.map { (item: Any) -> (title: String, detail: String) in
(
title: String(describing: item),
detail: String(reflecting: type(of: item))
)
}
case let item?:
self.values = [
(
title: String(describing: item),
detail: String(reflecting: type(of: item))
)
]
default:
self.values = []
}
self.sectionTitle = title
self.tableView?.reloadData()
}
// MARK: UIViewController
override func viewDidLoad() {
super.viewDidLoad()
self.tableView.estimatedRowHeight = 60
self.tableView.rowHeight = UITableView.automaticDimension
}
// MARK: UITableViewDataSource
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.values.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "UITableViewCell", for: indexPath)
let value = self.values[indexPath.row]
cell.textLabel?.text = value.title
cell.detailTextLabel?.text = value.detail
return cell
}
// MARK: UITableViewDelegate
override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return self.sectionTitle
}
// MARK: Private
var values: [(title: String, detail: String)] = []
var sectionTitle: String?
}
| mit | e5c72a3073fe29d357e4d7ace9a38813 | 24.488636 | 109 | 0.545698 | 5.511057 | false | false | false | false |
jsslai/Action | Carthage/Checkouts/RxSwift/RxExample/Extensions/CLLocationManager+Rx.swift | 1 | 7599 | //
// CLLocationManager+Rx.swift
// RxCocoa
//
// Created by Carlos García on 8/7/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
import CoreLocation
#if !RX_NO_MODULE
import RxSwift
import RxCocoa
#endif
extension Reactive where Base: CLLocationManager {
/**
Reactive wrapper for `delegate`.
For more information take a look at `DelegateProxyType` protocol documentation.
*/
public var delegate: DelegateProxy {
return RxCLLocationManagerDelegateProxy.proxyForObject(base)
}
// MARK: Responding to Location Events
/**
Reactive wrapper for `delegate` message.
*/
public var didUpdateLocations: Observable<[CLLocation]> {
return delegate.methodInvoked(#selector(CLLocationManagerDelegate.locationManager(_:didUpdateLocations:)))
.map { a in
return try castOrThrow([CLLocation].self, a[1])
}
}
/**
Reactive wrapper for `delegate` message.
*/
public var didFailWithError: Observable<NSError> {
return delegate.methodInvoked(#selector(CLLocationManagerDelegate.locationManager(_:didFailWithError:)))
.map { a in
return try castOrThrow(NSError.self, a[1])
}
}
#if os(iOS) || os(OSX)
/**
Reactive wrapper for `delegate` message.
*/
public var didFinishDeferredUpdatesWithError: Observable<NSError?> {
return delegate.methodInvoked(#selector(CLLocationManagerDelegate.locationManager(_:didFinishDeferredUpdatesWithError:)))
.map { a in
return try castOptionalOrThrow(NSError.self, a[1])
}
}
#endif
#if os(iOS)
// MARK: Pausing Location Updates
/**
Reactive wrapper for `delegate` message.
*/
public var didPauseLocationUpdates: Observable<Void> {
return delegate.methodInvoked(#selector(CLLocationManagerDelegate.locationManagerDidPauseLocationUpdates(_:)))
.map { _ in
return ()
}
}
/**
Reactive wrapper for `delegate` message.
*/
public var didResumeLocationUpdates: Observable<Void> {
return delegate.methodInvoked( #selector(CLLocationManagerDelegate.locationManagerDidResumeLocationUpdates(_:)))
.map { _ in
return ()
}
}
// MARK: Responding to Heading Events
/**
Reactive wrapper for `delegate` message.
*/
public var didUpdateHeading: Observable<CLHeading> {
return delegate.methodInvoked(#selector(CLLocationManagerDelegate.locationManager(_:didUpdateHeading:)))
.map { a in
return try castOrThrow(CLHeading.self, a[1])
}
}
// MARK: Responding to Region Events
/**
Reactive wrapper for `delegate` message.
*/
public var didEnterRegion: Observable<CLRegion> {
return delegate.methodInvoked(#selector(CLLocationManagerDelegate.locationManager(_:didEnterRegion:)))
.map { a in
return try castOrThrow(CLRegion.self, a[1])
}
}
/**
Reactive wrapper for `delegate` message.
*/
public var didExitRegion: Observable<CLRegion> {
return delegate.methodInvoked(#selector(CLLocationManagerDelegate.locationManager(_:didExitRegion:)))
.map { a in
return try castOrThrow(CLRegion.self, a[1])
}
}
#endif
#if os(iOS) || os(OSX)
/**
Reactive wrapper for `delegate` message.
*/
@available(OSX 10.10, *)
public var didDetermineStateForRegion: Observable<(state: CLRegionState, region: CLRegion)> {
return delegate.methodInvoked(#selector(CLLocationManagerDelegate.locationManager(_:didDetermineState:for:)))
.map { a in
let stateNumber = try castOrThrow(NSNumber.self, a[1])
let state = CLRegionState(rawValue: stateNumber.intValue) ?? CLRegionState.unknown
let region = try castOrThrow(CLRegion.self, a[2])
return (state: state, region: region)
}
}
/**
Reactive wrapper for `delegate` message.
*/
public var monitoringDidFailForRegionWithError: Observable<(region: CLRegion?, error: NSError)> {
return delegate.methodInvoked(#selector(CLLocationManagerDelegate.locationManager(_:monitoringDidFailFor:withError:)))
.map { a in
let region = try castOptionalOrThrow(CLRegion.self, a[1])
let error = try castOrThrow(NSError.self, a[2])
return (region: region, error: error)
}
}
/**
Reactive wrapper for `delegate` message.
*/
public var didStartMonitoringForRegion: Observable<CLRegion> {
return delegate.methodInvoked(#selector(CLLocationManagerDelegate.locationManager(_:didStartMonitoringFor:)))
.map { a in
return try castOrThrow(CLRegion.self, a[1])
}
}
#endif
#if os(iOS)
// MARK: Responding to Ranging Events
/**
Reactive wrapper for `delegate` message.
*/
public var didRangeBeaconsInRegion: Observable<(beacons: [CLBeacon], region: CLBeaconRegion)> {
return delegate.methodInvoked(#selector(CLLocationManagerDelegate.locationManager(_:didRangeBeacons:in:)))
.map { a in
let beacons = try castOrThrow([CLBeacon].self, a[1])
let region = try castOrThrow(CLBeaconRegion.self, a[2])
return (beacons: beacons, region: region)
}
}
/**
Reactive wrapper for `delegate` message.
*/
public var rangingBeaconsDidFailForRegionWithError: Observable<(region: CLBeaconRegion, error: NSError)> {
return delegate.methodInvoked(#selector(CLLocationManagerDelegate.locationManager(_:rangingBeaconsDidFailFor:withError:)))
.map { a in
let region = try castOrThrow(CLBeaconRegion.self, a[1])
let error = try castOrThrow(NSError.self, a[2])
return (region: region, error: error)
}
}
// MARK: Responding to Visit Events
/**
Reactive wrapper for `delegate` message.
*/
@available(iOS 8.0, *)
public var didVisit: Observable<CLVisit> {
return delegate.methodInvoked(#selector(CLLocationManagerDelegate.locationManager(_:didVisit:)))
.map { a in
return try castOrThrow(CLVisit.self, a[1])
}
}
#endif
// MARK: Responding to Authorization Changes
/**
Reactive wrapper for `delegate` message.
*/
public var didChangeAuthorizationStatus: Observable<CLAuthorizationStatus> {
return delegate.methodInvoked(#selector(CLLocationManagerDelegate.locationManager(_:didChangeAuthorization:)))
.map { a in
let number = try castOrThrow(NSNumber.self, a[1])
return CLAuthorizationStatus(rawValue: Int32(number.intValue)) ?? .notDetermined
}
}
}
fileprivate func castOrThrow<T>(_ resultType: T.Type, _ object: Any) throws -> T {
guard let returnValue = object as? T else {
throw RxCocoaError.castingError(object: object, targetType: resultType)
}
return returnValue
}
fileprivate func castOptionalOrThrow<T>(_ resultType: T.Type, _ object: Any) throws -> T? {
if NSNull().isEqual(object) {
return nil
}
guard let returnValue = object as? T else {
throw RxCocoaError.castingError(object: object, targetType: resultType)
}
return returnValue
}
| mit | 58c62e4364ea7b45bdb966f2b903dfa4 | 30.786611 | 130 | 0.633276 | 5.196306 | false | false | false | false |
GreenvilleCocoa/ChristmasDelivery | ChristmasDelivery/Building.swift | 1 | 2355 | //
// Building.swift
// ChristmasDelivery
//
// Created by Marcus Smith on 12/8/14.
// Copyright (c) 2014 GreenvilleCocoaheads. All rights reserved.
//
import SpriteKit
class Building: SKSpriteNode {
let type: BuildingType
init(texture: SKTexture!, color: UIColor!, size: CGSize, type: BuildingType) {
self.type = type
super.init(texture: texture, color: color, size: size)
name = "building"
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented, stop calling it")
}
convenience init(type: BuildingType, buildingSize: CGSize) {
var textureName: String?
switch type {
case .House:
textureName = "house.png"
case .HouseWithChimney:
textureName = "house.png"
case .ClockTower:
textureName = "clockTower.png"
}
let texture = SKTexture(imageNamed: textureName!)
self.init(texture: texture, color: UIColor.clearColor(), size: buildingSize, type: type)
self.physicsBody = SKPhysicsBody(texture: texture, size: buildingSize)
self.physicsBody!.categoryBitMask = PhysicsCategory.Hazard
self.physicsBody!.contactTestBitMask = PhysicsCategory.Present|PhysicsCategory.Santa|PhysicsCategory.Sleigh|PhysicsCategory.Reindeer
self.physicsBody!.dynamic = false
self.physicsBody!.affectedByGravity = false
if type == .HouseWithChimney {
let chimneySize: CGSize = CGSize(width: buildingSize.width / 5.0, height: buildingSize.height / 2.0)
print("Chimney size \(chimneySize)")
let chimney = SKSpriteNode(imageNamed: "chimney.png")
chimney.size = chimneySize
chimney.physicsBody = SKPhysicsBody(rectangleOfSize: chimneySize)
chimney.physicsBody!.categoryBitMask = PhysicsCategory.Chimney
chimney.physicsBody!.contactTestBitMask = PhysicsCategory.Present|PhysicsCategory.Santa|PhysicsCategory.Sleigh|PhysicsCategory.Reindeer
chimney.physicsBody!.affectedByGravity = false
chimney.physicsBody!.dynamic = false
self.addChild(chimney)
chimney.position = CGPoint(x: buildingSize.width / 4.0, y: buildingSize.height / 2.0)
}
}
}
| mit | ca32c5e233887fd80371297aa051a33f | 38.25 | 147 | 0.65138 | 4.485714 | false | false | false | false |
mrdepth/EVEUniverse | Legacy/Neocom/Neocom/ContractInfoInteractor.swift | 2 | 2569 | //
// ContractInfoInteractor.swift
// Neocom
//
// Created by Artem Shimanski on 11/12/18.
// Copyright © 2018 Artem Shimanski. All rights reserved.
//
import Foundation
import Futures
import CloudData
import EVEAPI
class ContractInfoInteractor: TreeInteractor {
typealias Presenter = ContractInfoPresenter
typealias Content = ESI.Result<Value>
weak var presenter: Presenter?
required init(presenter: Presenter) {
self.presenter = presenter
}
struct Value {
var contract: ESI.Contracts.Contract
var bids: [ESI.Contracts.Bid]?
var items: [ESI.Contracts.Item]?
var locations: [Int64: EVELocation]?
var contacts: [Int64: Contact]?
}
var api = Services.api.current
func load(cachePolicy: URLRequest.CachePolicy) -> Future<Content> {
guard let contract = presenter?.view?.input else {return .init(.failure(NCError.invalidInput(type: type(of: self))))}
let progress = Progress(totalUnitCount: 4)
let api = self.api
return Services.sde.performBackgroundTask { context -> Content in
let bids = try? progress.performAsCurrent(withPendingUnitCount: 1) {api.contractBids(contractID: Int64(contract.contractID), cachePolicy: cachePolicy)}.get()
let items = try? progress.performAsCurrent(withPendingUnitCount: 1) {api.contractItems(contractID: Int64(contract.contractID), cachePolicy: cachePolicy)}.get()
let locationIDs = [contract.startLocationID, contract.endLocationID].compactMap {$0}
let contactIDs = ([contract.acceptorID, contract.assigneeID, contract.issuerID] + (bids?.value.map {$0.bidderID} ?? []))
.filter{$0 > 0}
.map{Int64($0)}
let locations = try? progress.performAsCurrent(withPendingUnitCount: 1) {api.locations(with: Set(locationIDs))}.get()
let contacts = try? progress.performAsCurrent(withPendingUnitCount: 1) {api.contacts(with: Set(contactIDs))}.get()
let value = Value(contract: contract,
bids: bids?.value,
items: items?.value,
locations: locations,
contacts: contacts)
let expires = [bids?.expires, items?.expires].compactMap{$0}.min()
return ESI.Result(value: value, expires: expires, metadata: nil)
}
}
private var didChangeAccountObserver: NotificationObserver?
func configure() {
didChangeAccountObserver = NotificationCenter.default.addNotificationObserver(forName: .didChangeAccount, object: nil, queue: .main) { [weak self] _ in
_ = self?.presenter?.reload(cachePolicy: .useProtocolCachePolicy).then(on: .main) { presentation in
self?.presenter?.view?.present(presentation, animated: true)
}
}
}
}
| lgpl-2.1 | 45133ff876f335d52bbfa39c9571b043 | 37.328358 | 162 | 0.728583 | 3.832836 | false | false | false | false |
Ben21hao/edx-app-ios-new | Source/DownloadsAccessoryView.swift | 1 | 5509 | //
// DownloadsAccessoryView.swift
// edX
//
// Created by Akiva Leffert on 9/24/15.
// Copyright © 2015 edX. All rights reserved.
//
import UIKit
class DownloadsAccessoryView : UIView {
enum State {
case Available
case Downloading
case Done
}
private let downloadButton = UIButton(type: .System)
private let downloadSpinner = SpinnerView(size: .Medium, color: .Primary)
private let iconFontSize : CGFloat = 15
private let countLabel : UILabel = UILabel()
override init(frame : CGRect) {
state = .Available
itemCount = nil
super.init(frame: frame)
// downloadButton.tintColor = OEXStyles.sharedStyles().neutralBase()
// downloadButton.contentEdgeInsets = UIEdgeInsetsMake(15, 10, 15, 10)
// downloadButton.titleLabel?.font = UIFont.init(name: "FontAwesome", size: 20)
downloadButton.setContentCompressionResistancePriority(UILayoutPriorityRequired, forAxis: .Horizontal)
countLabel.setContentCompressionResistancePriority(UILayoutPriorityRequired, forAxis: .Horizontal)
downloadSpinner.setContentCompressionResistancePriority(UILayoutPriorityRequired, forAxis: .Horizontal)
self.addSubview(downloadButton)
self.addSubview(downloadSpinner)
self.addSubview(countLabel)
// This view is atomic from an accessibility point of view
self.isAccessibilityElement = true
downloadSpinner.accessibilityTraits = UIAccessibilityTraitNotEnabled;
countLabel.accessibilityTraits = UIAccessibilityTraitNotEnabled;
downloadButton.accessibilityTraits = UIAccessibilityTraitNotEnabled;
// downloadButton.backgroundColor = UIColor.redColor()
downloadSpinner.stopAnimating()
downloadSpinner.snp_makeConstraints {make in
make.center.equalTo(self)
}
downloadButton.snp_makeConstraints {make in
make.trailing.equalTo(self)
make.top.equalTo(self)
make.bottom.equalTo(self)
make.width.equalTo(39)
}
countLabel.snp_makeConstraints {make in
make.leading.equalTo(self)
make.centerY.equalTo(self)
make.trailing.equalTo(downloadButton.imageView!.snp_leading).offset(-6)
}
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// private func useIcon(icon : Icon?) {
// downloadButton.setImage(icon?.imageWithFontSize(iconFontSize), forState:.Normal)
//// downloadButton.setTitle("\u{0041}", forState: .Normal) //开始f0ed 云f299 圆f058
// }
var downloadAction : (() -> Void)? = nil {
didSet {
downloadButton.oex_removeAllActions()
downloadButton.oex_addAction({ _ in self.downloadAction?() }, forEvents: .TouchUpInside)
}
}
var itemCount : Int? {
didSet {
let count = itemCount ?? 0
let text = (count > 0 ? "\(count)" : "")
let styledText = CourseOutlineItemView.detailFontStyle.attributedStringWithText(text)
countLabel.attributedText = styledText
}
}
var state : State {
didSet {
switch state {
case .Available:
// useIcon(.CloudDownload)
downloadButton.setImage(UIImage.init(named: "no_download"), forState: .Normal)
downloadSpinner.hidden = true
downloadButton.userInteractionEnabled = true
downloadButton.hidden = false
self.userInteractionEnabled = true
countLabel.hidden = false
if let count = itemCount {
let message = Strings.downloadManyVideos(videoCount: count)
self.accessibilityLabel = message
}
else {
self.accessibilityLabel = Strings.download
}
self.accessibilityTraits = UIAccessibilityTraitButton
case .Downloading:
downloadSpinner.startAnimating()
downloadSpinner.hidden = false
downloadButton.userInteractionEnabled = true
self.userInteractionEnabled = true
downloadButton.hidden = true
countLabel.hidden = true
self.accessibilityLabel = Strings.downloading
self.accessibilityTraits = UIAccessibilityTraitButton
case .Done:
// useIcon(.CheckCircle)
downloadButton.setImage(UIImage.init(named: "had_download"), forState: .Normal)
downloadButton.tintColor = OEXStyles.sharedStyles().neutralBase()
downloadSpinner.hidden = true
self.userInteractionEnabled = false
downloadButton.hidden = false
countLabel.hidden = false
if let count = itemCount {
let message = Strings.downloadManyVideos(videoCount: count)
self.accessibilityLabel = message
}
else {
self.accessibilityLabel = Strings.downloaded
}
self.accessibilityTraits = UIAccessibilityTraitStaticText
}
}
}
}
| apache-2.0 | a798288b8dd19b481a8b19a8f54c4c15 | 36.671233 | 111 | 0.596545 | 5.851064 | false | false | false | false |
HugoBoscDucros/HBAutocomplete | AutocompleteTestProject/ViewControllers/SearchAddressViewController.swift | 1 | 2750 | //
// SearchAddressViewController.swift
// AutocompleteTestProject
//
// Created by Hugo Bosc-Ducros on 21/06/2019.
// Copyright © 2019 Hugo Bosc-Ducros. All rights reserved.
//
import UIKit
import HBAutocomplete
import MapKit
class SearchAddressViewController: UITableViewController, HBAutoCompleteActionsDelegate {
var searchController = UISearchController(searchResultsController: nil)
var autocomplete: HBAutocomplete!
var autocompleteDataSource = PlaceAutocompleteDataSource()
override func viewDidLoad() {
super.viewDidLoad()
self.loadSettings()
}
private func loadSettings() {
if #available(iOS 11.0, *) {
self.navigationItem.largeTitleDisplayMode = .automatic
self.navigationItem.searchController = searchController
self.navigationItem.hidesSearchBarWhenScrolling = false
self.navigationItem.searchController?.hidesNavigationBarDuringPresentation = false
} else {
// Fallback on earlier versions
}
self.autocomplete = HBAutocomplete(self.searchController.searchBar, tableView: self.tableView)
self.autocomplete.dataSource = self.autocompleteDataSource
self.autocomplete.store = AutocompleteStore(.place)
self.autocomplete.historicalImage = UIImage(named: "SearchHistory")
searchController.searchBar.placeholder = "Search an address"
definesPresentationContext = false
searchController.searchBar.showsCancelButton = false
searchController.obscuresBackgroundDuringPresentation = false
self.tableView.tableFooterView = UIView()
self.autocomplete.actionsDelegate = self
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
self.searchController.searchBar.resignFirstResponder()
}
//MARK: - Autocomplete Action delegate
func didSelect(autocomplete: HBAutocomplete, index: Int, suggestion: String, data: Any?) {
if self.autocomplete.selectedData is MKMapItem {
self.performSegue(withIdentifier: "MapSegue", sender: self)
self.autocomplete.addToHistory()
}
}
func didSelectCustomAction(autocomplete: HBAutocomplete, index: Int) {
//Do something
}
// 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?) {
if segue.identifier == "MapSegue", let item = self.autocomplete.selectedData as? MKMapItem, let mapVC = segue.destination as? MapViewController {
mapVC.mapItem = item
}
}
}
| mit | c8e4ec29092e63d3a69b092b5d0e9abd | 34.701299 | 153 | 0.694071 | 5.422091 | false | false | false | false |
dreamsxin/swift | validation-test/Reflection/reflect_Int32.swift | 1 | 2152 | // RUN: rm -rf %t && mkdir -p %t
// RUN: %target-build-swift -lswiftSwiftReflectionTest %s -o %t/reflect_Int32
// RUN: %target-run %target-swift-reflection-test %t/reflect_Int32 2>&1 | FileCheck %s --check-prefix=CHECK-%target-ptrsize
// REQUIRES: objc_interop
// REQUIRES: executable_test
import SwiftReflectionTest
class TestClass {
var t: Int32
init(t: Int32) {
self.t = t
}
}
var obj = TestClass(t: 123)
reflect(object: obj)
// CHECK-64: Reflecting an object.
// CHECK-64: Instance pointer in child address space: 0x{{[0-9a-fA-F]+}}
// CHECK-64: Type reference:
// CHECK-64: (class reflect_Int32.TestClass)
// CHECK-64: Type info:
// CHECK-64: (class_instance size=20 alignment=16 stride=32 num_extra_inhabitants=0
// CHECK-64: (field name=t offset=16
// CHECK-64: (struct size=4 alignment=4 stride=4 num_extra_inhabitants=0
// CHECK-64: (field name=_value offset=0
// CHECK-64: (builtin size=4 alignment=4 stride=4 num_extra_inhabitants=0)))))
// CHECK-32: Reflecting an object.
// CHECK-32: Instance pointer in child address space: 0x{{[0-9a-fA-F]+}}
// CHECK-32: Type reference:
// CHECK-32: (class reflect_Int32.TestClass)
// CHECK-32: Type info:
// CHECK-32: (class_instance size=16 alignment=16 stride=16 num_extra_inhabitants=0
// CHECK-32: (field name=t offset=12
// CHECK-32: (struct size=4 alignment=4 stride=4 num_extra_inhabitants=0
// CHECK-32: (field name=_value offset=0
// CHECK-32: (builtin size=4 alignment=4 stride=4 num_extra_inhabitants=0)))))
reflect(any: obj)
// CHECK-64: Reflecting an existential.
// CHECK-64: Instance pointer in child address space: 0x{{[0-9a-fA-F]+}}
// CHECK-64: Type reference:
// CHECK-64: (class reflect_Int32.TestClass)
// CHECK-64: Type info:
// CHECK-64: (reference kind=strong refcounting=native)
// CHECK-32: Reflecting an existential.
// CHECK-32: Instance pointer in child address space: 0x{{[0-9a-fA-F]+}}
// CHECK-32: Type reference:
// CHECK-32: (class reflect_Int32.TestClass)
// CHECK-32: Type info:
// CHECK-32: (reference kind=strong refcounting=native)
doneReflecting()
// CHECK-64: Done.
// CHECK-32: Done.
| apache-2.0 | 57cb6bc5d0c6445443ec33891aeb0c9c | 31.606061 | 123 | 0.685874 | 3.078684 | false | true | false | false |
kasketis/netfox | netfox/Core/NFXProtocol.swift | 1 | 6020 | //
// NFXProtocol.swift
// netfox
//
// Copyright © 2016 netfox. All rights reserved.
//
import Foundation
@objc
open class NFXProtocol: URLProtocol {
static let nfxInternalKey = "com.netfox.NFXInternal"
private lazy var session: URLSession = { [unowned self] in
return URLSession(configuration: .default, delegate: self, delegateQueue: nil)
}()
private let model = NFXHTTPModel()
private var response: URLResponse?
private var responseData: NSMutableData?
override open class func canInit(with request: URLRequest) -> Bool {
return canServeRequest(request)
}
override open class func canInit(with task: URLSessionTask) -> Bool {
if #available(iOS 13.0, macOS 10.15, *) {
if task is URLSessionWebSocketTask {
return false
}
}
guard let request = task.currentRequest else { return false }
return canServeRequest(request)
}
private class func canServeRequest(_ request: URLRequest) -> Bool {
guard NFX.sharedInstance().isEnabled() else {
return false
}
guard URLProtocol.property(forKey: NFXProtocol.nfxInternalKey, in: request) == nil,
let url = request.url,
(url.absoluteString.hasPrefix("http") || url.absoluteString.hasPrefix("https")) else {
return false
}
let absoluteString = url.absoluteString
guard !NFX.sharedInstance().getIgnoredURLs().contains(where: { absoluteString.hasPrefix($0) }) else {
return false
}
let regexMatches = NFX.sharedInstance().getIgnoredURLsRegexes()
.map({return $0.matches(url.absoluteString)})
.reduce(false) {$0 || $1}
guard regexMatches == false else {
return false
}
return true
}
override open func startLoading() {
model.saveRequest(request)
let mutableRequest = (request as NSURLRequest).mutableCopy() as! NSMutableURLRequest
URLProtocol.setProperty(true, forKey: NFXProtocol.nfxInternalKey, in: mutableRequest)
session.dataTask(with: mutableRequest as URLRequest).resume()
}
override open func stopLoading() {
session.getTasksWithCompletionHandler { dataTasks, _, _ in
dataTasks.forEach { $0.cancel() }
self.session.invalidateAndCancel()
}
}
override open class func canonicalRequest(for request: URLRequest) -> URLRequest {
return request
}
}
extension NSRegularExpression {
convenience init(_ pattern: String) {
do {
try self.init(pattern: pattern)
} catch {
preconditionFailure("Illegal regular expression: \(pattern).")
}
}
func matches(_ string: String) -> Bool {
let range = NSRange(location: 0, length: string.count)
return firstMatch(in: string, options: [], range: range) != nil
}
}
extension NFXProtocol: URLSessionDataDelegate {
public func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data) {
responseData?.append(data)
client?.urlProtocol(self, didLoad: data)
}
public func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive response: URLResponse, completionHandler: @escaping (URLSession.ResponseDisposition) -> Void) {
self.response = response
responseData = NSMutableData()
client?.urlProtocol(self, didReceive: response, cacheStoragePolicy: NFX.swiftSharedInstance.cacheStoragePolicy)
completionHandler(.allow)
}
public func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) {
defer {
if let error = error {
client?.urlProtocol(self, didFailWithError: error)
} else {
client?.urlProtocolDidFinishLoading(self)
}
}
guard let request = task.originalRequest else {
return
}
model.saveRequestBody(request)
model.logRequest(request)
if error != nil {
model.saveErrorResponse()
} else if let response = response {
let data = (responseData ?? NSMutableData()) as Data
model.saveResponse(response, data: data)
}
NFXHTTPModelManager.shared.add(model)
}
public func urlSession(_ session: URLSession, task: URLSessionTask, willPerformHTTPRedirection response: HTTPURLResponse, newRequest request: URLRequest, completionHandler: @escaping (URLRequest?) -> Void) {
let updatedRequest: URLRequest
if URLProtocol.property(forKey: NFXProtocol.nfxInternalKey, in: request) != nil {
let mutableRequest = (request as NSURLRequest).mutableCopy() as! NSMutableURLRequest
URLProtocol.removeProperty(forKey: NFXProtocol.nfxInternalKey, in: mutableRequest)
updatedRequest = mutableRequest as URLRequest
} else {
updatedRequest = request
}
client?.urlProtocol(self, wasRedirectedTo: updatedRequest, redirectResponse: response)
completionHandler(updatedRequest)
}
public func urlSession(_ session: URLSession, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) {
let wrappedChallenge = URLAuthenticationChallenge(authenticationChallenge: challenge, sender: NFXAuthenticationChallengeSender(handler: completionHandler))
client?.urlProtocol(self, didReceive: wrappedChallenge)
}
#if !os(OSX)
public func urlSessionDidFinishEvents(forBackgroundURLSession session: URLSession) {
client?.urlProtocolDidFinishLoading(self)
}
#endif
}
| mit | 8a3e84647a675154866b21f8e7ed4b4b | 35.259036 | 211 | 0.636651 | 5.407907 | false | false | false | false |
jarocht/iOS-Bootcamp-Summer2015 | HW9/GoogleMapsDemo/GoogleMapsDemo/ViewController.swift | 1 | 4633 | //
// ViewController.swift
// GoogleMapsDemo
//
// Created by Jonathan Engelsma on 6/4/15.
// Copyright (c) 2015 Jonathan Engelsma. All rights reserved.
//
import UIKit
import Foundation
class ViewController: UIViewController, CLLocationManagerDelegate, GMSMapViewDelegate {
let locationManager = CLLocationManager()
var locations: [Location] = []
override func viewDidLoad() {
super.viewDidLoad()
self.locationManager.delegate = self
self.locationManager.requestWhenInUseAuthorization()
var cameraSwitzerland = GMSCameraPosition.cameraWithLatitude(47.5000142,longitude: 8.73299, zoom: 4)
let mapView = GMSMapView.mapWithFrame(CGRectZero, camera: cameraSwitzerland)
mapView.settings.compassButton = true
self.view = mapView
loadLocations()
//PIN FOR EACH LOC
for loc in locations {
var marker = GMSMarker()
marker.position = CLLocationCoordinate2DMake(loc.lat, loc.long)
marker.title = loc.company
marker.snippet = loc.phone
marker.appearAnimation = kGMSMarkerAnimationPop
marker.icon = UIImage(named: "Pin")
marker.map = mapView
}
mapView.delegate = self
}
func loadLocations(){
// open and parse a file named data.json dragged into my iOS project
var filePath = NSBundle.mainBundle().pathForResource("locations", ofType:"json")
var data = NSData(contentsOfFile:filePath!)
var parseError: NSError?
let parsedObject: AnyObject? = NSJSONSerialization.JSONObjectWithData(data!,
options: NSJSONReadingOptions.AllowFragments,
error:&parseError)
if let topLevelObj = parsedObject as? NSDictionary {
if let data = topLevelObj["data"] as? NSArray {
//var contact: Contact
var location: Location
for item in data {
var coord = (item[2] as! String)
var coordArr = split(coord) {$0 == "," || $0 == " "}
location = Location (company: item[0] as! String, phone: item[1] as! String, Latitude: (coordArr[0] as NSString).doubleValue , Longitude: (coordArr[1] as NSString).doubleValue)
self.locations.append(location)
}
}
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
updateLocation(true)
}
func locationManager(manager: CLLocationManager!, didChangeAuthorizationStatus status: CLAuthorizationStatus) {
updateLocation(false)
updateLocation(true)
}
func updateLocation(running: Bool) {
let mapView = self.view as! GMSMapView
let status = CLLocationManager.authorizationStatus()
if running {
if (CLAuthorizationStatus.AuthorizedWhenInUse == status) {
locationManager.startUpdatingLocation()
mapView.myLocationEnabled = true
mapView.settings.myLocationButton = true
}
} else {
locationManager.stopUpdatingLocation()
mapView.settings.myLocationButton = false
mapView.myLocationEnabled = false
}
}
//Clicked Marker
func mapView(mapView: GMSMapView!, didTapMarker marker: GMSMarker!) -> Bool {
println("You just tapped the \(marker.title) marker!")
return false
}
//Override annotation with infoView
func mapView(mapView: GMSMapView!, markerInfoWindow marker: GMSMarker!) -> UIView! {
var infoWindow = NSBundle.mainBundle().loadNibNamed("InfoWindow", owner: self, options: nil).first! as! CustomInfoWindow
infoWindow.TitleLabel.text = marker.title
infoWindow.SubTitleLabel.text = marker.snippet
return infoWindow
}
//Clicked annotation (infoView)
func mapView(mapView: GMSMapView!, didTapInfoWindowOfMarker marker: GMSMarker!) {
let alertController = UIAlertController(title: marker.title, message:
marker.snippet, preferredStyle: UIAlertControllerStyle.Alert)
alertController.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.Default,handler: nil))
self.presentViewController(alertController, animated: true, completion: nil)
}
}
| gpl-2.0 | 3e3bcd140aefb2b09f183287f69cdffa | 35.480315 | 196 | 0.629829 | 5.425059 | false | false | false | false |
isgustavo/AnimatedMoviesMakeMeCry | iOS/Animated Movies Make Me Cry/Animated Movies Make Me Cry/AnimatedMovieController.swift | 1 | 4787 | //
// AnimatedMovieController.swift
// Animated Movies Make Me Cry
//
// Created by Gustavo F Oliveira on 6/1/16.
// Copyright © 2016 Gustavo F Oliveira. All rights reserved.
//
import UIKit
import Firebase
struct Movie {
var name: String!
var thumbnail: UIImage!
var video: String!
var like: Int!
init(name: String, thumbnail: UIImage, video: String, like: Int) {
self.name = name
self.thumbnail = thumbnail
self.video = video
self.like = like
}
}
class AnimatedMovieController: UIViewController, UITableViewDataSource, UITableViewDelegate {
@IBOutlet weak var tableView: UITableView!
var database: FIRDatabase!
var storage: FIRStorage!
var animatedMovies: [Movie] = [Movie]()
var loading: Bool = true {
didSet {
self.tableView.reloadData()
self.tableView.scrollEnabled = true
}
}
// MARK: - Lifecycle app
override func viewDidLoad() {
super.viewDidLoad()
self.tableView.dataSource = self
self.tableView.delegate = self
//Initialize Database
self.database = FIRDatabase.database()
self.storage = FIRStorage.storage()
self.prepareValuesForUse()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table View Data Source
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if self.loading {
return 3
} else {
return animatedMovies.count
}
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
if self.loading {
let cell = tableView.dequeueReusableCellWithIdentifier("LoadingCell", forIndexPath: indexPath) as! LoadingAnimatedMovieCell
return cell
} else {
let cell = tableView.dequeueReusableCellWithIdentifier("MovieCell", forIndexPath: indexPath) as! AnimatedMovieCell
let movie = self.animatedMovies[indexPath.row]
cell.thumbnailImage.image = movie.thumbnail
cell.movieName.text = movie.name
return cell
}
}
// MARK: - Table View Delegate
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
if self.loading {
return CGFloat(200.0)
} else {
return CGFloat(270.0)
}
}
// MARK: - Animated Movie Controller methods
func prepareValuesForUse() {
//Listen for when child nodes get added to the collection
let moviesRef = database.reference().child("movies")
var downloadThumbStack: Int = 0
moviesRef.observeEventType(.Value, withBlock: { (snapshot) -> Void in
let postDict = snapshot.value as! [String: AnyObject]
self.animatedMovies = [Movie]()
for (_, value) in postDict.enumerate() {
let name = value.1["name"] as! String
let thumb = value.1["thumbnail"] as! String
let video = value.1["video"] as! String
let likes = value.1["likes"] as! Int
let gsReference = self.storage.referenceForURL(thumb)
let downloadTask = gsReference.dataWithMaxSize(25 * 1024 * 1024) { (data, error) -> Void in
if (error != nil) {
print("Uh-oh, an error occurred!\(error)")
} else {
let image: UIImage! = UIImage(data: data!)
let movie = Movie(name: name, thumbnail: image, video: video, like: likes)
self.animatedMovies.append(movie)
if downloadThumbStack == 0 {
self.loading = false
}
}
}
// Observe changes in status
downloadTask.observeStatus(.Resume) { (snapshot) -> Void in
downloadThumbStack += 1
}
downloadTask.observeStatus(.Success) { (snapshot) -> Void in
downloadThumbStack -= 1
}
downloadTask.observeStatus(.Failure) { (snapshot) -> Void in
downloadThumbStack -= 1
}
}
})
}
}
| apache-2.0 | 732dc0c6a11479b5d99f6358b918c5c0 | 30.695364 | 135 | 0.536356 | 5.420159 | false | false | false | false |
waterskier2007/NVActivityIndicatorView | NVActivityIndicatorView/Animations/NVActivityIndicatorAnimationBallCirclePath.swift | 1 | 1805 | //
// NVActivityIndicatorAnimationInfinityPath.swift
//
//
// Created by Brendan Kirchner on 8/5/15.
//
//
import UIKit
class NVActivityIndicatorAnimationBallCirclePath: NVActivityIndicatorAnimationDelegate {
func setUpAnimationInLayer(layer: CALayer, size: CGSize, color: UIColor) {
circleInLayer(layer, size: size, color: color)
}
func circleInLayer(layer: CALayer, size: CGSize, color: UIColor) {
let minDimen = min(size.width, size.height)
let circleSize = size.width / 5
let radius = minDimen / 2
let circleDuration: CFTimeInterval = 1
// Left animation
let start = CGPoint(x: (layer.bounds.width - minDimen) / 2, y: layer.bounds.height / 2)
let rect = CGRect(x: start.x, y: start.y - radius, width: 2 * radius, height: 2 * radius)
let path = CGPathCreateWithEllipseInRect(rect, nil)
let animation = CAKeyframeAnimation(keyPath: "position")
animation.path = path
animation.removedOnCompletion = false
animation.repeatCount = HUGE
animation.duration = circleDuration
animation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionLinear)
animation.calculationMode = kCAAnimationPaced
// Draw circles
let circle = NVActivityIndicatorShape.Circle.createLayerWith(size: CGSize(width: circleSize, height: circleSize), color: color)
let frame = CGRect(
x: (layer.bounds.width - size.width) / 2,
y: layer.bounds.height / 2,
width: circleSize,
height: circleSize
)
circle.frame = frame
circle.addAnimation(animation, forKey: "animation")
layer.addSublayer(circle)
}
}
| mit | e55d6c1b805f09f611abfc717aa0d12e | 33.711538 | 135 | 0.637119 | 4.737533 | false | false | false | false |
coderQuanjun/PigTV | GYJTV/GYJTV/Classes/Profile/Controller/SettingViewController.swift | 1 | 2106 | //
// SettingViewController.swift
// GYJTV
//
// Created by zcm_iOS on 2017/6/19.
// Copyright © 2017年 Quanjun. All rights reserved.
//
import UIKit
class SettingViewController: BaseProfileViewController {
override func viewDidLoad() {
super.viewDidLoad()
navigationController?.navigationBar.tintColor = UIColor.white
}
override var preferredStatusBarStyle: UIStatusBarStyle{
return .lightContent
}
///数据处理
override func loadProfileData() {
super.loadProfileData()
// 1.第一组数据
let section0Model = SettingSectionModel()
section0Model.sectionHeight = 5
let section0Item = SettingItemModel(icon: "", title: "开播提醒", "", .onswitch)
section0Model.sectionArr.append(section0Item)
let section1Item = SettingItemModel(icon: "", title: "移动流量提醒", "", .onswitch)
section0Model.sectionArr.append(section1Item)
let section2Item = SettingItemModel(icon: "", title: "网络环境优化@objc ", "", .onswitch)
section0Model.sectionArr.append(section2Item)
settingArrar.append(section0Model)
// 2.第二组数据
let section1Model = SettingSectionModel()
section1Model.sectionHeight = 5
let section1Item0 = SettingItemModel(icon: "", title: "绑定手机", "未绑定", .arrowDetail)
section1Model.sectionArr.append(section1Item0)
let section1Item1 = SettingItemModel(title: "意见反馈")
section1Model.sectionArr.append(section1Item1)
let section1Item2 = SettingItemModel(title: "直播公约")
section1Model.sectionArr.append(section1Item2)
let section1Item3 = SettingItemModel(title: "关于我们")
section1Model.sectionArr.append(section1Item3)
let section1Item4 = SettingItemModel(title: "我要好评")
section1Model.sectionArr.append(section1Item4)
settingArrar.append(section1Model)
// 3.刷新表格
tableView.reloadData()
}
}
| mit | a95d0d7b6dcd94aeb272a27131757b3a | 32.15 | 91 | 0.65812 | 4.118012 | false | false | false | false |
jzucker2/JZToolKit | JZToolKit/Classes/Core/ToolKitViewController.swift | 1 | 4305 | //
// ToolKitViewController.swift
// Pods
//
// Created by Jordan Zucker on 2/17/17.
//
//
import UIKit
// This is a programmatic view controller to consolidate repeated programmatic set up
open class ToolKitViewController: UIViewController/*, Observer*/ {
// public var kvoContext: Int = 0
//
// open class var observerResponses: [String:Selector]? {
// return nil
// }
// public func updateKVO(with actions: KVOActions, oldValue: NSObject? = nil) {
// guard let observingKeyPaths = type(of: self).observerResponses else {
// print("No observer responses exist")
// return
// }
// for (keyPath, _) in observingKeyPaths {
// if actions.contains(.removeOldValue) {
// oldValue?.removeObserver(self, forKeyPath: keyPath, context: &kvoContext)
// }
// if actions.contains(.remove) {
// observedObject?.removeObserver(self, forKeyPath: keyPath, context: &kvoContext)
// }
// if actions.contains(.add) {
// observedObject?.addObserver(self, forKeyPath: keyPath, options: [.new, .old, .initial], context: &kvoContext)
// }
// }
// }
// open var observedObject: NSObject? {
// didSet {
// print("hey there: \(#function)")
// updateKVO(with: .propertyObserverActions, oldValue: oldValue)
// }
// }
// open override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
// print("self: \(self.debugDescription) \(#function) context: \(context)")
// if context == &kvoContext {
// guard let observingKeyPaths = type(of: self).observerResponses else {
// print("No observing Key Paths exist")
// return
// }
// guard let actualKeyPath = keyPath, let action = observingKeyPaths[actualKeyPath] else {
// fatalError("we should have had an action for this keypath since we are observing it")
// }
// let mainQueueUpdate = DispatchWorkItem(qos: .userInitiated, flags: [.enforceQoS], block: { [weak self] in
// // _ = self?.perform(action)
// _ = self?.perform(action)
// })
// DispatchQueue.main.async(execute: mainQueueUpdate)
// } else {
// super.observeValue(forKeyPath: keyPath, of: object, change: change, context: context)
// }
// }
open class func embedInNavigationController(navigationControllerType: UINavigationController.Type = UINavigationController.self, tabBarItem: UITabBarItem? = nil) -> UINavigationController {
let rootViewController = self.init()
let navController = navigationControllerType.init(rootViewController: rootViewController)
if let actualTabBarItem = tabBarItem {
navController.tabBarItem = actualTabBarItem
}
return navController
}
public required init() {
super.init(nibName: nil, bundle: nil)
}
// Figure out something about this, maybe implement myself
public required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// This creates a view programmatically for you, assumes you are not using storyboards
open override func loadView() {
let bounds = UIScreen.main.bounds
let loadingView = UIView(frame: bounds)
loadingView.backgroundColor = .white
self.view = loadingView
}
open override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
// open override func viewWillAppear(_ animated: Bool) {
// super.viewWillAppear(animated)
// updateKVO(with: .add)
// }
//
// open override func viewDidDisappear(_ animated: Bool) {
// super.viewDidDisappear(animated)
// updateKVO(with: .remove)
// }
open override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// deinit {
// observedObject = nil
// }
}
| mit | 328f85837ed5266da522b64c972a4563 | 35.794872 | 193 | 0.606504 | 4.629032 | false | false | false | false |
tunespeak/AlamoRecord | Example/Pods/KeyboardSpy/KeyboardSpy/Classes/KeyboardSpy.swift | 1 | 5503 |
/*
The MIT License (MIT)
Copyright (c) 2017 Dalton Hinterscher
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.
*/
public class KeyboardSpy {
private static var _defaultSpy: KeyboardSpy?
private static var defaultSpy: KeyboardSpy {
if _defaultSpy == nil {
_defaultSpy = KeyboardSpy()
}
return _defaultSpy!
}
private var spies: [KeyboardSpyAgent] = []
private init() {
NotificationCenter.default.addObserver(self,
selector: #selector(keyboardWillShow(notification:)),
name: NSNotification.Name.UIKeyboardWillShow,
object: nil)
NotificationCenter.default.addObserver(self,
selector: #selector(keyboardDidShow(notification:)),
name: NSNotification.Name.UIKeyboardDidShow,
object: nil)
NotificationCenter.default.addObserver(self,
selector: #selector(keyboardWillHide(notification:)),
name: NSNotification.Name.UIKeyboardWillHide,
object: nil)
NotificationCenter.default.addObserver(self,
selector: #selector(keyboardDidHide(notification:)),
name: NSNotification.Name.UIKeyboardDidHide,
object: nil)
NotificationCenter.default.addObserver(self,
selector: #selector(keyboardWillChangeFrame(notification:)),
name: NSNotification.Name.UIKeyboardWillChangeFrame,
object: nil)
NotificationCenter.default.addObserver(self,
selector: #selector(keyboardDidChangeFrame(notification:)),
name: NSNotification.Name.UIKeyboardDidChangeFrame,
object: nil)
}
@objc private dynamic func keyboardWillShow(notification: Notification) {
processKeyboardEvent(.willShow, notification: notification)
}
@objc private dynamic func keyboardDidShow(notification: Notification) {
processKeyboardEvent(.didShow, notification: notification)
}
@objc private dynamic func keyboardWillHide(notification: Notification) {
processKeyboardEvent(.willHide, notification: notification)
}
@objc private dynamic func keyboardDidHide(notification: Notification) {
processKeyboardEvent(.didHide, notification: notification)
}
@objc private dynamic func keyboardWillChangeFrame(notification: Notification) {
processKeyboardEvent(.willChangeFrame, notification: notification)
}
@objc private dynamic func keyboardDidChangeFrame(notification: Notification) {
processKeyboardEvent(.didChangeFrame, notification: notification)
}
private func processKeyboardEvent(_ event: KeyboardSpyEvent, notification: Notification) {
let keyboardInfo = KeyboardSpyInfo(notification: notification)
for spy in spies {
if spy.keyboardEventsToSpyOn.contains(event) {
spy.keyboardSpyEventProcessed(event: event, keyboardInfo: keyboardInfo)
}
}
}
private func agentIsAlreadySpying(_ agent: KeyboardSpyAgent) -> Bool {
for spy in spies {
if spy.description == agent.description {
return true
}
}
return false
}
private func indexOfAgent(_ agent: KeyboardSpyAgent) -> Int? {
for (i, spy) in spies.enumerated() {
if agent.description == spy.description {
return i
}
}
return nil
}
public class func spy(on agent: KeyboardSpyAgent) {
if !defaultSpy.agentIsAlreadySpying(agent) {
defaultSpy.spies.append(agent)
}
}
public class func unspy(on agent: KeyboardSpyAgent) {
if let index = defaultSpy.indexOfAgent(agent) {
defaultSpy.spies.remove(at: index)
}
}
}
| mit | 1acc6e22d0dca64f2e4156f9be5d1e61 | 43.739837 | 147 | 0.597129 | 6.047253 | false | false | false | false |
huangboju/QMUI.swift | QMUI.swift/QMUIKit/UIComponents/QMUIPopupContainerView.swift | 1 | 33048 | //
// QMUIPopupContainerView.swift
// QMUI.swift
//
// Created by 黄伯驹 on 2017/7/10.
// Copyright © 2017年 伯驹 黄. All rights reserved.
//
enum QMUIPopupContainerViewLayoutDirection {
case above
case below
}
/**
* 带箭头的小tips浮层,自带 imageView 和 textLabel,可展示简单的图文信息。
* QMUIPopupContainerView 支持以两种方式显示在界面上:
* 1. 添加到某个 UIView 上(适合于 viewController 切换时浮层跟着一起切换的场景),这种场景只能手动隐藏浮层。
* 2. 在 QMUIPopupContainerView 自带的 UIWindow 里显示(适合于用完就消失的场景,不要涉及界面切换),这种场景支持点击空白地方自动隐藏浮层。
*
* 使用步骤:
* 1. 调用 init 方法初始化。
* 2. 选择一种显示方式:
* 2.1 如果要添加到某个 UIView 上,则先设置浮层 hidden = YES,然后调用 addSubview: 把浮层添加到目标 UIView 上。
* 2.2 如果是轻量的场景用完即走,则 init 完浮层即可,无需设置 hidden,也无需调用 addSubview:,在后面第 4 步里会自动把浮层添加到 UIWindow 上显示出来。
* 3. 在适当的时机(例如 layoutSubviews: 或 viewDidLayoutSubviews: 或在 show 之前)调用 layoutWithTargetView: 让浮层参考目标 view 布局,或者调用 layoutWithTargetRectInScreenCoordinate: 让浮层参考基于屏幕坐标系里的一个 rect 来布局。
* 4. 调用 showWithAnimated: 或 showWithAnimated:completion: 显示浮层。
* 5. 调用 hideWithAnimated: 或 hideWithAnimated:completion: 隐藏浮层。
*
* @warning 如果使用方法 2.2,并且没有打开 automaticallyHidesWhenUserTap 属性,则记得在适当的时机(例如 viewWillDisappear:)隐藏浮层。
*
* 如果默认功能无法满足需求,可继承它重写一个子类,继承要点:
* 1. 初始化时要做的事情请放在 didInitialized 里。
* 2. 所有 subviews 请加到 contentView 上。
* 3. 通过重写 sizeThatFitsInContentView:,在里面返回当前 subviews 的大小,控件最终会被布局为这个大小。
* 4. 在 layoutSubviews: 里,所有 subviews 请相对于 contentView 布局。
*/
class QMUIPopupContainerView: UIControl {
var backgroundLayer: CAShapeLayer!
var arrowMinX: CGFloat = 0
var isDebug: Bool = false
/// 在浮层显示时,点击空白地方是否要自动隐藏浮层,仅在用方法 2 显示时有效。
/// 默认为 false,也即需要手动调用代码去隐藏浮层。
var automaticallyHidesWhenUserTap: Bool = false
/// 所有subview都应该添加到contentView上,默认contentView.userInteractionEnabled = NO,需要事件操作时自行打开
private(set) var contentView: UIView!
/// 预提供的UIImageView,默认为nil,调用到的时候才初始化
lazy var imageView: UIImageView = {
let imageView = UIImageView()
imageView.contentMode = .center
contentView.addSubview(imageView)
return imageView
}()
/// 预提供的UILabel,默认为nil,调用到的时候才初始化。默认支持多行。
lazy var textLabel: UILabel = {
let textLabel = UILabel()
textLabel.font = UIFontMake(12)
textLabel.textColor = UIColorBlack
textLabel.numberOfLines = 0
contentView.addSubview(textLabel)
return textLabel
}()
/// 圆角矩形气泡内的padding(不包括三角箭头),默认是(8, 8, 8, 8)
var contentEdgeInsets: UIEdgeInsets = UIEdgeInsets(top: 8, left: 8, bottom: 8, right: 8)
/// 调整imageView的位置,默认为UIEdgeInsetsZero。top/left正值表示往下/右方偏移,bottom/right仅在对应位置存在下一个子View时生效(例如只有同时存在imageView和textLabel时,imageEdgeInsets.right才会生效)。
var imageEdgeInsets: UIEdgeInsets = .zero
/// 调整textLabel的位置,默认为UIEdgeInsetsZero。top/left/bottom/right的作用同<i>imageEdgeInsets</i>
var textEdgeInsets: UIEdgeInsets = .zero
/// 三角箭头的大小,默认为 CGSizeMake(18, 9)
var arrowSize = CGSize(width: 18, height: 9)
/// 最大宽度(指整个控件的宽度,而不是contentView部分),默认为CGFLOAT_MAX
var maximumWidth: CGFloat = 0
/// 最小宽度(指整个控件的宽度,而不是contentView部分),默认为0
var minimumWidth: CGFloat = 0
/// 最大高度(指整个控件的高度,而不是contentView部分),默认为CGFLOAT_MAX
var maximumHeight: CGFloat = .infinity
/// 最小高度(指整个控件的高度,而不是contentView部分),默认为0
var minimumHeight: CGFloat = 0
/// 计算布局时期望的默认位置,默认为QMUIPopupContainerViewLayoutDirectionAbove,也即在目标的上方
var preferLayoutDirection: QMUIPopupContainerViewLayoutDirection = .above
/// 最终的布局方向(preferLayoutDirection只是期望的方向,但有可能那个方向已经没有剩余空间可摆放控件了,所以会自动变换)
private(set) var currentLayoutDirection: QMUIPopupContainerViewLayoutDirection = .above
/// 最终布局时箭头距离目标边缘的距离,默认为5
var distanceBetweenTargetRect: CGFloat = 5
/// 最终布局时与父节点的边缘的临界点,默认为(10, 10, 10, 10)
var safetyMarginsOfSuperview = UIEdgeInsets(top: 10, left: 10, bottom: 10, right: 10)
override var backgroundColor: UIColor? {
get {
return super.backgroundColor
}
set {
super.backgroundColor = UIColorClear
backgroundLayer.fillColor = newValue?.cgColor
}
}
var highlightedBackgroundColor: UIColor?
/// 当使用方法 2 显示并且打开了 automaticallyHidesWhenUserTap 时,可修改背景遮罩的颜色,默认为 UIColorMask,若非使用方法 2,或者没有打开 automaticallyHidesWhenUserTap,则背景遮罩为透明(可视为不存在背景遮罩)
var maskViewBackgroundColor: UIColor? {
didSet {
if let popupWindow = popupWindow {
popupWindow.rootViewController?.view.backgroundColor = maskViewBackgroundColor
}
}
}
var shadowColor: UIColor? {
didSet {
backgroundLayer.shadowColor = shadowColor?.cgColor
}
}
var borderColor: UIColor? {
didSet {
backgroundLayer.strokeColor = borderColor?.cgColor
}
}
var borderWidth: CGFloat = 0 {
didSet {
backgroundLayer.lineWidth = borderWidth
}
}
var cornerRadius: CGFloat = 0 {
didSet {
setNeedsLayout()
}
}
override var isHighlighted: Bool {
didSet {
if let highlightedBackgroundColor = highlightedBackgroundColor {
backgroundLayer.fillColor = isHighlighted ? highlightedBackgroundColor.cgColor : backgroundColor?.cgColor
}
}
}
override func sizeThatFits(_ size: CGSize) -> CGSize {
var _size = size
_size.width = min(size.width, superviewIfExist!.bounds.width - safetyMarginsOfSuperview.horizontalValue)
_size.height = min(size.height, superviewIfExist!.bounds.height - safetyMarginsOfSuperview.verticalValue)
let contentLimitSize = self.contentSize(in: _size)
let contentSize = sizeThatFitsInContentView(contentLimitSize)
let resultSize = sizeWithContentSize(contentSize, sizeThatFits: size)
return resultSize
}
override func layoutSubviews() {
super.layoutSubviews()
let arrowSize = self.arrowSize
let roundedRect = CGRect(x: borderWidth / 2.0,
y: borderWidth / 2.0 + (currentLayoutDirection == .above ? 0 : arrowSize.height),
width: bounds.width - borderWidth,
height: bounds.height - arrowSize.height - borderWidth)
let cornerRadius = self.cornerRadius
let leftTopArcCenter = CGPoint(x: roundedRect.minX + cornerRadius, y: roundedRect.minY + cornerRadius)
let leftBottomArcCenter = CGPoint(x: leftTopArcCenter.x, y: roundedRect.maxY - cornerRadius)
let rightTopArcCenter = CGPoint(x: roundedRect.maxX - cornerRadius, y: leftTopArcCenter.y)
let rightBottomArcCenter = CGPoint(x: rightTopArcCenter.x, y: leftBottomArcCenter.y)
let path = UIBezierPath()
path.move(to: CGPoint(x: leftTopArcCenter.x, y: roundedRect.minY))
path.addArc(withCenter: leftTopArcCenter, radius: cornerRadius, startAngle: .pi * 1.5, endAngle: .pi, clockwise: false)
path.addLine(to: CGPoint(x: roundedRect.minX, y: leftBottomArcCenter.y))
path.addArc(withCenter: leftBottomArcCenter, radius: cornerRadius, startAngle: .pi, endAngle: .pi * 0.5, clockwise: false)
if currentLayoutDirection == .above {
// 让开,我要开始开始画三角形了,箭头向下
path.addLine(to: CGPoint(x: arrowMinX, y: roundedRect.maxY))
path.addLine(to: CGPoint(x: arrowMinX + arrowSize.width / 2, y: roundedRect.maxY + arrowSize.height))
path.addLine(to: CGPoint(x: arrowMinX + arrowSize.width, y: roundedRect.maxY))
}
path.addLine(to: CGPoint(x: rightBottomArcCenter.x, y: roundedRect.maxY))
path.addArc(withCenter: rightBottomArcCenter, radius: cornerRadius, startAngle: .pi * 0.5, endAngle: 0, clockwise: false)
path.addLine(to: CGPoint(x: roundedRect.maxX, y: rightTopArcCenter.y))
path.addArc(withCenter: rightTopArcCenter, radius: cornerRadius, startAngle: 0.0, endAngle: .pi * 1.5, clockwise: false)
if currentLayoutDirection == .below {
// 箭头向上
path.addLine(to: CGPoint(x: arrowMinX + arrowSize.width, y: roundedRect.minY))
path.addLine(to: CGPoint(x: arrowMinX + arrowSize.width / 2, y: roundedRect.minY - arrowSize.height))
path.addLine(to: CGPoint(x: arrowMinX, y: roundedRect.minY))
}
path.close()
backgroundLayer.path = path.cgPath
backgroundLayer.shadowPath = path.cgPath
backgroundLayer.frame = bounds
layoutDefaultSubviews()
}
private func layoutDefaultSubviews() {
contentView.frame = CGRect(x: borderWidth + contentEdgeInsets.left,
y: (currentLayoutDirection == .above ? borderWidth : arrowSize.height + borderWidth) + contentEdgeInsets.top,
width: bounds.width - borderWidth * 2 - contentEdgeInsets.horizontalValue,
height: bounds.height - arrowSize.height - borderWidth * 2 - contentEdgeInsets.verticalValue)
// contentView的圆角取一个比整个path的圆角小的最大值(极限情况下如果self.contentEdgeInsets.left比self.cornerRadius还大,那就意味着contentView不需要圆角了)
// 这么做是为了尽量去掉contentView对内容不必要的裁剪,以免有些东西被裁剪了看不到
let contentViewCornerRadius = abs(fmin(contentView.frame.minX - cornerRadius, 0))
contentView.layer.cornerRadius = contentViewCornerRadius
let isImageViewShowing = isSubviewShowing(imageView)
let isTextLabelShowing = isSubviewShowing(textLabel)
if isImageViewShowing {
imageView.sizeToFit()
imageView.frame = imageView.frame.setXY(imageEdgeInsets.left, flat(contentView.bounds.height.center(imageView.frame.height) + imageEdgeInsets.top))
}
if isTextLabelShowing {
let textLabelMinX = (isImageViewShowing ? ceil(imageView.frame.maxX + imageEdgeInsets.right) : 0) + textEdgeInsets.left
let textLabelLimitSize = CGSize(width: ceil(contentView.bounds.width - textLabelMinX),
height: ceil(contentView.bounds.height - textEdgeInsets.top - textEdgeInsets.bottom))
let textLabelSize = textLabel.sizeThatFits(textLabelLimitSize)
let textLabelOrigin = CGPoint(x: textLabelMinX,
y: flat(contentView.bounds.height.center(ceil(textLabelSize.height)) + textEdgeInsets.top))
textLabel.frame = CGRect(x: textLabelOrigin.x, y: textLabelOrigin.y, width: textLabelLimitSize.width, height: ceil(textLabelSize.height))
}
}
// MARK: - Private Tools
private func isSubviewShowing(_ subview: UIView?) -> Bool {
guard let subview = subview, !subview.isHidden, subview.superview != nil else {
return false
}
return true
}
private func initPopupContainerViewWindowIfNeeded() {
if popupWindow == nil {
popupWindow = QMUIPopupContainerViewWindow()
popupWindow?.backgroundColor = UIColorClear
popupWindow?.windowLevel = UIWindow.Level(rawValue: UIWindowLevelQMUIAlertView)
let viewController = QMUIPopContainerViewController()
(viewController.view as? QMUIPopContainerMaskControl)?.popupContainerView = self
if automaticallyHidesWhenUserTap {
viewController.view.backgroundColor = maskViewBackgroundColor
} else {
viewController.view.backgroundColor = UIColorClear
}
viewController.supportedOrientationMask = QMUIHelper.visibleViewController?.supportedInterfaceOrientations
popupWindow?.rootViewController = viewController // 利用 rootViewController 来管理横竖屏
popupWindow?.rootViewController?.view.addSubview(self)
}
}
/// 根据一个给定的大小,计算出符合这个大小的内容大小
private func contentSize(in size: CGSize) -> CGSize {
let contentSize = CGSize(width: size.width - contentEdgeInsets.horizontalValue - borderWidth * 2, height: size.height - arrowSize.height - borderWidth * 2)
return contentSize
}
/// 根据内容大小和外部限制的大小,计算出合适的self size(包含箭头)
private func sizeWithContentSize(_ contentSize: CGSize, sizeThatFits: CGSize) -> CGSize {
var resultWidth = contentSize.width + contentEdgeInsets.horizontalValue + borderWidth * 2
resultWidth = min(resultWidth, sizeThatFits.width) // 宽度不能超过传进来的size.width
resultWidth = max(fmin(resultWidth, maximumWidth), minimumWidth) // 宽度必须在最小值和最大值之间
resultWidth = ceil(resultWidth)
var resultHeight = contentSize.height + contentEdgeInsets.verticalValue + arrowSize.height + borderWidth * 2
resultHeight = min(resultHeight, sizeThatFits.height)
resultHeight = max(fmin(resultHeight, maximumHeight), minimumHeight)
resultHeight = ceil(resultHeight)
return CGSize(width: resultWidth, height: resultHeight)
}
var isShowing: Bool {
let isShowingIfAddedToView = superview != nil && !isHidden && popupWindow == nil
let isShowingIfInWindow = superview != nil && popupWindow != nil && !popupWindow!.isHidden
return isShowingIfAddedToView || isShowingIfInWindow
}
/**
* 即将显示时的回调
* 注:如果需要使用例如 didShowBlock 的时机,请使用 @showWithAnimated:completion: 的 completion 参数来实现。
* @argv animated 是否需要动画
*/
var willShowClosure: ((_ animated: Bool) -> Void)?
/**
* 即将隐藏时的回调
* @argv hidesByUserTap 用于区分此次隐藏是否因为用户手动点击空白区域导致浮层被隐藏
* @argv animated 是否需要动画
*/
var willHideClosure: ((_ hidesByUserTap: Bool, _ animated: Bool) -> Void)?
/**
* 已经隐藏后的回调
* @argv hidesByUserTap 用于区分此次隐藏是否因为用户手动点击空白区域导致浮层被隐藏
*/
var didHideClosure: ((_ hidesByUserTap: Bool) -> Void)?
private var popupWindow: QMUIPopupContainerViewWindow?
private weak var previousKeyWindow: UIWindow?
fileprivate var hidesByUserTap = false
override init(frame: CGRect) {
super.init(frame: frame)
didInitialized()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
didInitialized()
}
override func hitTest(_ point: CGPoint, with event: UIEvent?) -> UIView? {
let result = super.hitTest(point, with: event)
if result == contentView {
return self
}
return result
}
/**
* 相对于某个 view 布局(布局后箭头不一定会水平居中)
* @param targetView 注意如果这个 targetView 自身的布局发生变化,需要重新调用 layoutWithTargetView:,否则浮层的布局不会自动更新。
*/
func layout(with targetView: UIView) {
var targetViewFrameInMainWindow = CGRect.zero
let mainWindow = (UIApplication.shared.delegate!.window!)!
if targetView.window == mainWindow {
targetViewFrameInMainWindow = targetView.convert(targetView.bounds, to: targetView.window)
} else {
let targetViewFrameInLocalWindow = targetView.convert(targetView.bounds, to: targetView.window)
targetViewFrameInMainWindow = mainWindow.convert(targetViewFrameInLocalWindow, to: targetView.window)
}
layout(with: targetViewFrameInMainWindow, inReferenceWindow: targetView.window)
}
/**
* 相对于给定的 itemRect 布局(布局后箭头不一定会水平居中)
* @param targetRect 注意这个 rect 应该是处于屏幕坐标系里的 rect,所以请自行做坐标系转换。
*/
func layoutWithTargetRectInScreenCoordinate(_ targetRect: CGRect) {
layout(with: targetRect, inReferenceWindow: (UIApplication.shared.delegate!.window)!)
}
private func layout(with targetRect: CGRect, inReferenceWindow window: UIWindow?) {
let superview = superviewIfExist
let isLayoutInWindowMode = !(superview != nil && popupWindow == nil)
let superviewBoundsInWindow = isLayoutInWindowMode ? window!.bounds : superview!.convert(superview!.bounds, to: window)
var tipSize = sizeThatFits(CGSize(width: maximumWidth, height: maximumHeight))
let preferredTipWidth = tipSize.width
// 保护tips最往左只能到达self.safetyMarginsOfSuperview.left
let a = targetRect.midX - tipSize.width / 2
var tipMinX = fmax(superviewBoundsInWindow.minX + safetyMarginsOfSuperview.left, a)
var tipMaxX = tipMinX + tipSize.width
if tipMaxX + safetyMarginsOfSuperview.right > superviewBoundsInWindow.maxX {
// 右边超出了
// 先尝试把右边超出的部分往左边挪,看是否会令左边到达临界点
let distanceCanMoveToLeft = tipMaxX - (superviewBoundsInWindow.maxX - safetyMarginsOfSuperview.right)
if tipMinX - distanceCanMoveToLeft >= superviewBoundsInWindow.minX + safetyMarginsOfSuperview.left {
// 可以往左边挪
tipMinX -= distanceCanMoveToLeft
} else {
// 不可以往左边挪,那么让左边靠到临界点,然后再把宽度减小,以让右边处于临界点以内
tipMinX = superviewBoundsInWindow.minX + safetyMarginsOfSuperview.left
tipMaxX = superviewBoundsInWindow.maxX - safetyMarginsOfSuperview.right
tipSize.width = fmin(tipSize.width, tipMaxX - tipMinX)
}
}
// 经过上面一番调整,可能tipSize.width发生变化,一旦宽度变化,高度要重新计算,所以重新调用一次sizeThatFits
let tipWidthChanged = tipSize.width != preferredTipWidth
if tipWidthChanged {
tipSize = sizeThatFits(tipSize)
}
currentLayoutDirection = preferLayoutDirection
// 检查当前的最大高度是否超过任一方向的剩余空间,如果是,则强制减小最大高度,避免后面计算布局选择方向时死循环
let canShowAtAbove = canTipShowAtSpecifiedLayoutDirect(.above, targetRect: targetRect, tipSize: tipSize)
let canShowAtBelow = canTipShowAtSpecifiedLayoutDirect(.below, targetRect: targetRect, tipSize: tipSize)
if !canShowAtAbove && !canShowAtBelow {
// 上下都没有足够的空间,所以要调整maximumHeight
let maximumHeightAbove = targetRect.minY - superviewBoundsInWindow.minY - distanceBetweenTargetRect - safetyMarginsOfSuperview.top
let maximumHeightBelow = superviewBoundsInWindow.maxY - safetyMarginsOfSuperview.bottom - distanceBetweenTargetRect - targetRect.maxY
maximumHeight = max(minimumHeight, max(maximumHeightAbove, maximumHeightBelow))
tipSize.height = maximumHeight
currentLayoutDirection = maximumHeightAbove > maximumHeightBelow ? .above : .below
print("\(self), 因为上下都不够空间,所以最大高度被强制改为\(maximumHeight), 位于目标的\(maximumHeightAbove > maximumHeightBelow ? "上方" : "下方")")
} else if currentLayoutDirection == .above && !canShowAtAbove {
currentLayoutDirection = .below
} else if currentLayoutDirection == .below && !canShowAtBelow {
currentLayoutDirection = .above
}
var tipMinY = tipMinYWithTargetRect(targetRect, tipSize: tipSize, preferLayoutDirection: currentLayoutDirection)
// 当上下的剩余空间都比最小高度要小的时候,tip会靠在safetyMargins范围内的上(下)边缘
if currentLayoutDirection == .above {
let tipMinYIfAlignSafetyMarginTop = superviewBoundsInWindow.minY + safetyMarginsOfSuperview.top
tipMinY = max(tipMinY, tipMinYIfAlignSafetyMarginTop)
} else if currentLayoutDirection == .below {
let tipMinYIfAlignSafetyMarginBottom = superviewBoundsInWindow.maxY - safetyMarginsOfSuperview.bottom - tipSize.height
tipMinY = min(tipMinY, tipMinYIfAlignSafetyMarginBottom)
}
// 上面计算得出的 tipMinX、tipMinY 是处于 window 坐标系里的,而浮层可能是以 addSubview: 的方式显示在某个 superview 上,所以要做一次坐标系转换
var origin = CGPoint(x: tipMinX, y: tipMinY)
origin = window!.convert(origin, to: superview)
tipMinX = origin.x
tipMinY = origin.y
frame = CGRectFlat(tipMinX, tipMinY, tipSize.width, tipSize.height)
// 调整浮层里的箭头的位置
let targetRectCenter = CGPoint(x: targetRect.midX, y: targetRect.midY)
let selfMidX = targetRectCenter.x - (superviewBoundsInWindow.minX + frame.minX)
arrowMinX = selfMidX - arrowSize.width / 2
setNeedsLayout()
if isDebug {
contentView.backgroundColor = UIColorTestGreen
borderColor = UIColorRed
borderWidth = PixelOne
imageView.backgroundColor = UIColorTestRed
textLabel.backgroundColor = UIColorTestBlue
}
}
private func canTipShowAtSpecifiedLayoutDirect(_ direction: QMUIPopupContainerViewLayoutDirection, targetRect itemRect: CGRect, tipSize: CGSize) -> Bool {
var canShow = false
let tipMinY = tipMinYWithTargetRect(itemRect, tipSize: tipSize, preferLayoutDirection: direction)
if direction == .above {
canShow = tipMinY >= safetyMarginsOfSuperview.top
} else if direction == .below {
canShow = tipMinY + tipSize.height + safetyMarginsOfSuperview.bottom <= superviewIfExist!.bounds.height
}
return canShow
}
private func tipMinYWithTargetRect(_ itemRect: CGRect, tipSize: CGSize, preferLayoutDirection direction: QMUIPopupContainerViewLayoutDirection) -> CGFloat {
var tipMinY: CGFloat = 0
if direction == .above {
tipMinY = itemRect.minY - tipSize.height - distanceBetweenTargetRect
} else if direction == .below {
tipMinY = itemRect.maxY + distanceBetweenTargetRect
}
return tipMinY
}
func show(with animated: Bool, completion: ((Bool) -> Void)? = nil) {
var isShowingByWindowMode = false
if superview == nil {
initPopupContainerViewWindowIfNeeded()
let viewController = popupWindow?.rootViewController as? QMUICommonViewController
viewController?.supportedOrientationMask = QMUIHelper.visibleViewController?.supportedInterfaceOrientations
previousKeyWindow = UIApplication.shared.keyWindow
popupWindow?.makeKeyAndVisible()
isShowingByWindowMode = true
} else {
isHidden = false
}
willShowClosure?(animated)
if animated {
if isShowingByWindowMode {
popupWindow?.alpha = 0
} else {
alpha = 0
}
layer.transform = CATransform3DMakeScale(0.98, 0.98, 1)
UIView.animate(withDuration: 0.4, delay: 0, usingSpringWithDamping: 0.3, initialSpringVelocity: 12, options: .curveLinear, animations: {
self.layer.transform = CATransform3DMakeScale(1, 1, 1)
}, completion: {
completion?($0)
})
UIView.animate(withDuration: 0.2, delay: 0, options: .curveLinear, animations: {
if isShowingByWindowMode {
self.popupWindow?.alpha = 1
} else {
self.alpha = 1
}
}, completion: nil)
} else {
if isShowingByWindowMode {
popupWindow?.alpha = 1
} else {
alpha = 1
}
completion?(true)
}
}
func hide(with animated: Bool, completion: ((Bool) -> Void)? = nil) {
willHideClosure?(hidesByUserTap, animated)
let isShowingByWindowMode = popupWindow != nil
if animated {
UIView.animate(withDuration: 0.2, delay: 0, options: .curveLinear, animations: {
if isShowingByWindowMode {
self.popupWindow?.alpha = 0
} else {
self.alpha = 0
}
}, completion: { _ in
self.hideCompletion(with: isShowingByWindowMode, completion: completion)
})
} else {
hideCompletion(with: isShowingByWindowMode, completion: completion)
}
}
private func hideCompletion(with windowMode: Bool, completion: ((Bool) -> Void)? = nil) {
if windowMode {
// 恢复 keyWindow 之前做一下检查,避免类似问题 https://github.com/QMUI/QMUI_iOS/issues/90
if UIApplication.shared.keyWindow == popupWindow {
previousKeyWindow?.makeKey()
}
// iOS 9 下(iOS 8 和 10 都没问题)需要主动移除,才能令 rootViewController 和 popupWindow 立即释放,不影响后续的 layout 判断,如果不加这两句,虽然 popupWindow 指针被置为 nil,但其实对象还存在,View 层级关系也还在
// https://github.com/QMUI/QMUI_iOS/issues/75
removeFromSuperview()
popupWindow?.rootViewController = nil
popupWindow?.isHidden = true
popupWindow = nil
} else {
isHidden = true
}
completion?(true)
didHideClosure?(hidesByUserTap)
hidesByUserTap = false
}
var superviewIfExist: UIView? {
let isAddedToCustomView = superview != nil && popupWindow == nil
if isAddedToCustomView {
return superview!
}
// https://github.com/QMUI/QMUI_iOS/issues/76
let window = (UIApplication.shared.delegate!.window!)!
let shouldLayoutBaseOnPopupWindow = popupWindow != nil && popupWindow!.bounds.size == window.bounds.size
let result = shouldLayoutBaseOnPopupWindow ? popupWindow : window
return result?.rootViewController?.view
}
// MARK: - UISubclassingHooks
/// 子类重写,在初始化时做一些操作
open func didInitialized() {
backgroundLayer = CAShapeLayer()
backgroundLayer.shadowOffset = CGSize(width: 0, height: 2)
backgroundLayer.shadowOpacity = 1
backgroundLayer.shadowRadius = 10
layer.addSublayer(backgroundLayer)
contentView = UIView()
contentView.clipsToBounds = true
addSubview(contentView)
// 由于浮层是在调用 showWithAnimated: 时才会被添加到 window 上,所以 appearance 也是在 showWithAnimated: 后才生效,这太晚了,会导致 showWithAnimated: 之前用到那些支持 appearance 的属性值都不准确,所以这里手动提前触发。
updateAppearance()
}
/// 子类重写,告诉父类subviews的合适大小
open func sizeThatFitsInContentView(_ size: CGSize) -> CGSize {
// 如果没内容则返回自身大小
if !isSubviewShowing(imageView) && !isSubviewShowing(textLabel) {
let selfSize = contentSize(in: bounds.size)
return selfSize
}
var resultSize = CGSize.zero
let isImageViewShowing = isSubviewShowing(imageView)
if isImageViewShowing {
let imageViewSize = imageView.sizeThatFits(size)
resultSize.width += ceil(imageViewSize.width) + imageEdgeInsets.left
resultSize.height += ceil(imageViewSize.height) + imageEdgeInsets.top
}
let isTextLabelShowing = isSubviewShowing(textLabel)
if isTextLabelShowing {
let textLabelLimitSize = CGSize(width: size.width - resultSize.width - imageEdgeInsets.right, height: size.height)
let textLabelSize = textLabel.sizeThatFits(textLabelLimitSize)
resultSize.width += (isImageViewShowing ? imageEdgeInsets.right : 0) + ceil(textLabelSize.width) + textEdgeInsets.left
resultSize.height = max(resultSize.height, ceil(textLabelSize.height) + textEdgeInsets.top)
}
resultSize.width = min(size.width, resultSize.width)
resultSize.height = min(size.height, resultSize.height)
return resultSize
}
}
extension QMUIPopupContainerView {
fileprivate func updateAppearance() {
contentEdgeInsets = UIEdgeInsets(top: 8, left: 8, bottom: 8, right: 8)
arrowSize = CGSize(width: 18, height: 9)
maximumWidth = CGFloat.greatestFiniteMagnitude
minimumWidth = 0
maximumHeight = CGFloat.greatestFiniteMagnitude
minimumHeight = 0
preferLayoutDirection = .above
distanceBetweenTargetRect = 5
safetyMarginsOfSuperview = UIEdgeInsets(top: 10, left: 10, bottom: 10, right: 10)
backgroundColor = UIColorWhite
maskViewBackgroundColor = UIColorMask
highlightedBackgroundColor = nil
shadowColor = UIColor(r: 0, g: 0, b: 0, a: 0.1)
borderColor = UIColorGrayLighten
borderWidth = PixelOne
cornerRadius = 10
qmui_outsideEdge = .zero
}
}
class QMUIPopupContainerViewWindow: UIWindow {
// 避免 UIWindow 拦截掉事件,保证让事件继续往背后传递
override func hitTest(_ point: CGPoint, with event: UIEvent?) -> UIView? {
let result = super.hitTest(point, with: event)
if result == self {
return nil
}
return result
}
}
class QMUIPopContainerViewController: QMUICommonViewController {
override func loadView() {
let maskControl = QMUIPopContainerMaskControl()
view = maskControl
}
}
class QMUIPopContainerMaskControl: UIControl {
weak var popupContainerView: QMUIPopupContainerView?
override init(frame: CGRect) {
super.init(frame: frame)
addTarget(self, action: #selector(handleMaskEvent), for: .touchUpInside)
}
override func hitTest(_ point: CGPoint, with event: UIEvent?) -> UIView? {
let result = super.hitTest(point, with: event)
if result == self {
if popupContainerView != nil && !popupContainerView!.automaticallyHidesWhenUserTap {
return nil
}
}
return result
}
// 把点击遮罩的事件放在 addTarget: 里而不直接在 hitTest:withEvent: 里处理是因为 hitTest:withEvent: 总是会走两遍
@objc
private func handleMaskEvent(_: UIControl) {
if popupContainerView != nil && popupContainerView!.automaticallyHidesWhenUserTap {
popupContainerView!.hidesByUserTap = true
popupContainerView!.hide(with: true)
}
}
required init?(coder _: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
| mit | 853ca43404d0d9e55d45150836ddfb38 | 40.246479 | 180 | 0.663992 | 4.430408 | false | false | false | false |
manuelCarlos/Swift-Playgrounds | ProtocolsForDataModel.playground/Contents.swift | 1 | 7523 |
import UIKit
class SuperHero {
var name: String
var power: Int
init(name: String, power: Int){
self.name = name
self.power = power
}
}
/*:
Suppose we need to create a few heros for our game, say we want an Invisible Man and a Super Man. We can subclass Superhero and build our custom objects:
*/
class Flyinghero: SuperHero{
var position: CGPoint = .zero
func fly(from origin: CGPoint, to destination: CGPoint){
position = origin == position ? destination : position
}
}
class Invisiblehero: SuperHero{
private var alpha : CGFloat = 1.0
var vanish : () { alpha = alpha == 1 ? 0.0 : 1.0 }
}
let phantom = Invisiblehero(name: "phantom", power: 80)
phantom.vanish
let superMan = Flyinghero(name: "superman", power: 100)
superMan.fly(from: CGPoint.zero, to: CGPoint(x: 10, y: 10))
superMan.position
/*:
But what if we want a hero that has the ability to fly And be invisible?
We can't inherit from multiple super classes, as in C++ for example, and even if we could that comes with its own problems (diamand problem, I'm looking at you).
We could definitly keep using the approach that worked for the Fying and Invisible heros but if we keep adding objects it would quickly become clear that sharing a base class is not the smoothest approach to share our code's purpose, moreover what if we want to use value types for our data model?. We're all out of luck because structs don't support inheritance in swift.
*/
/*:
#### This is a job for SuperM... well, Protocols.
Classes, structures, enums are allowed to inherit from any number of protocols and protocols themselves can adopt other protocols making it easy share code without ever sharing a base class. This is a lot more flexible than inheritance. Let's see an example.
*/
/*:
> A familiar practice throughout the Swift's standart library is to name protocols according to their implicit intent:
* "Can do" protocols, describe what a type can "do", like Comparable, equatable, hashable, all end on "able".
* “Is a” protocols, that describe what kind of thing the type is: CollectionType, SequenceType, end on ...Type.
* "Can be" protocols defining type conversions like CustomStringConvertible end in ...Convertible.
*/
/*:
Lets start by defining a simple SuperHeroType protocol:
*/
protocol SuperHeroType {
var name : String { get }
var power: Int { get }
}
/*:
Since we'll want some super heros to be able to fly lets write a Flyable protocol defining a basic requiered implementation for a type. */
protocol Flyable {
var position: CGPoint {get set}
mutating func fly(from origin: CGPoint, to destination: CGPoint)
}
/*:
Now we create a structure that adopts the SuperHeroType protocol and an instance to test out. We're using a structure but we could choose to use class or enum in much the same way.
*/
struct FlyingHero: SuperHeroType, Flyable {
var name: String
var power: Int
var position: CGPoint
mutating func fly(from origin: CGPoint, to destination: CGPoint){
position = origin == position ? destination : position
}
}
/*:
How about a Invisible hero? Sure, no problem.
*/
protocol Invisiblable: SuperHeroType {
var alpha: CGFloat { get set }
var vanish: () { mutating get }
}
/*:
Since var vanish will be basicly the same in each InvisibleHero instance we might create, we can provide a default implementation of it in a protocol extension, like this:
*/
extension Invisiblable where Self: SuperHeroType{
var vanish : () { mutating alpha = alpha == 1 ? 0.0 : 1.0 }
}
struct InvisibleHero: Invisiblable {
var name: String
var power: Int
var alpha: CGFloat
// an alternative definition of vanish if we need to override the default
// var vanish : () { mutating alpha = alpha == 1 ? 1.0 : 0.0 }
}
/*:
Notice that since var vanish is defined beforehand in an extension we don't have to implement it to comform to Invisiblable, but we still have the choice to override it if we need to.
*/
/*:
Now we have the tools to create an invisible flying superhero. Lets call it FlyingPhantom?
*/
struct FlyingPhantom:Flyable, Invisiblable {
var name: String
var power: Int
var alpha: CGFloat
var position: CGPoint
mutating func fly(from origin: CGPoint, to destination: CGPoint){
position = origin == position ? destination : position
}
}
var batman: FlyingPhantom = FlyingPhantom(name: "Batman", power: 80, alpha: 1.0, position: CGPoint.zero)
var invisibleMan: InvisibleHero = InvisibleHero(name: "InvisibleMan", power: 80, alpha: 1.0)
var superman: FlyingHero = FlyingHero(name: "Superman", power: 100, position: CGPoint.zero)
/*:
## Going Generic (almost)
Say you want to make your super hero type vulnerable to an external source of damage. A Vulnerable protocol is the way to go:
>
protocol Vulnerable{
func suffer(damage: Damage)
}
What would be the type of Damage ? The thing is that superheros are usually vulnerable to diferent things so Damage needs to be a generic type. For now swift has two ways to make generic protocols:
1. Using Self
*/
protocol VulnerableSelf{
mutating func suffer(_ damage: Self)
}
struct SpiderMan: SuperHeroType, VulnerableSelf {
var name: String
var power: Int
mutating func suffer(_ damage: SpiderMan){
power -= 50
}
}
/*:
Self is a placeholder for your conforming type without having to know that type in advance. This is cool but it's also restrictive because it will only work if the paramater is of the same type as the function caller.
*/
/*:
2. Using AssociatedTypes
*/
protocol Vulnerable{
associatedtype Damage
mutating func suffer(_ damage: Damage)
}
struct SpiderBat: SuperHeroType, Vulnerable {
var name: String
var power: Int
typealias Damage = Int
mutating func suffer(_ damage: Damage){
// do something to damage
}
}
/*:
or
*/
struct FancySpiderBat < Damage>: SuperHeroType, Vulnerable {
var name: String
var power: Int
mutating func suffer(_ damage: Damage){
print("suffered some damage of \(damage)")
}
}
/*:
And then we create instances like this:
*/
var spiddy = SpiderBat(name: "SpiderBe", power: 30)
var fancySpiddy = FancySpiderBat < Int > (name: "SpiderBe", power: 30)
/*:
Because associatedtype Damage is not a concrete type, any type that conforms to the Vulnerable protocol needs to supply a solid real swift type at compile time. Which is why we use either a typealias to asign an Int to Damage or the <> notation when creating proper instances. This is still limiting because if we can choose any type of damage, we are stuck with that one choice. We can't choose to use more than one type.
You can still supply extra types inside the angle brackets used to abstract structures, but this is not much of an improvement and definitly not a soluction in any way to this problem.
*/
struct FancySpiderBat2 < Damage, OtherType>: SuperHeroType, Vulnerable {
var name: String
var power: Int
mutating func metaSuffer(_ damage: OtherType){
// do something to damage
}
mutating func suffer(_ damage: Damage){
// do something to damage
}
}
var fancySpiddy2 = FancySpiderBat2 < Int, String > (name: "SpiderBe", power: 30)
fancySpiddy2.suffer(44)
fancySpiddy2.metaSuffer("Dr. Who")
| mit | 290667409b2f47f2f19470ccdaa98182 | 27.698473 | 425 | 0.701423 | 3.916146 | false | false | false | false |
paul8263/ImageBoardBrowser | ImageBoardBrowser/ImageTagsTableViewController.swift | 1 | 3638 | //
// ImageTagsTableViewController.swift
// ImageBoardBrowser
//
// Created by Paul Zhang on 10/12/2016.
// Copyright © 2016 Paul Zhang. All rights reserved.
//
import UIKit
class ImageTagsTableViewController: UITableViewController {
var imageTagArray: [String]!
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()
tableView.tableFooterView = UIView()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
if let tabBarController = tabBarController as? MainTabBarController {
tabBarController.panGesture?.isEnabled = false
}
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
if let tabBarController = tabBarController as? MainTabBarController {
tabBarController.panGesture?.isEnabled = true
}
}
// MARK: - Table view data source
override func numberOfSections(in 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 imageTagArray.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "imageTagCell", for: indexPath)
cell.textLabel?.text = imageTagArray[indexPath.row]
return cell
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
}
override func tableView(_ tableView: UITableView, accessoryButtonTappedForRowWith indexPath: IndexPath) {
let tabBarController = self.tabBarController
let navigationController = tabBarController?.viewControllers?[2] as? UINavigationController
_ = navigationController?.popToRootViewController(animated: false)
let searchViewController = navigationController?.topViewController as! SearchViewController
searchViewController.searchedTags = imageTagArray[indexPath.row]
searchViewController.searchBar.text = searchViewController.searchedTags
searchViewController.performSearch()
tabBarController?.selectedIndex = 2
}
override func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? {
let addToFavouriteAction = UITableViewRowAction(style: .default, title: "Add") { (action, indexPath) in
FavouriteStorageHelper.addFavouriteTag(tag: self.imageTagArray[indexPath.row])
self.tableView.setEditing(false, animated: true)
}
addToFavouriteAction.backgroundColor = UIColor.orange
return [addToFavouriteAction]
}
override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
}
}
| mit | 9a88d6605d3c16dc20cdf27498f02ff7 | 38.532609 | 136 | 0.707176 | 5.856683 | false | false | false | false |
raymccrae/swift-htmlsaxparser | Sources/HTMLSAXParser/EscapeSpecialCharacters.swift | 1 | 5675 | //
// EscapeSpecialCharacters.swift
// HTMLSAXParser
//
// Created by Raymond Mccrae on 21/07/2017.
// Copyright © 2017 Raymond McCrae.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import Foundation
import CHTMLSAXParser
public enum HTMLQuoteCharacter: Character {
case none = "\0"
case singleQuote = "'"
case doubleQuote = "\""
var characterCode: CInt {
switch self {
case .none:
return 0
case .singleQuote:
return 39
case .doubleQuote:
return 34
}
}
}
public extension Data {
// swiftlint:disable:next function_parameter_count
fileprivate func encodeHTMLEntitiesBytes(_ outputLength: inout Int,
_ outputLengthBytes: UnsafeMutablePointer<CInt>,
_ inputLengthBytes: UnsafeMutablePointer<CInt>,
_ quoteCharacter: HTMLQuoteCharacter,
_ inputLength: Int,
_ loop: inout Bool,
_ bufferGrowthFactor: Double) -> Data? {
return self.withUnsafeBytes { (inputBytes: UnsafePointer<UInt8>) -> Data? in
let outputBufferCapacity = outputLength
let outputBuffer = UnsafeMutablePointer<UInt8>.allocate(capacity: outputBufferCapacity)
defer {
outputBuffer.deallocate(capacity: Int(outputBufferCapacity))
}
let result = htmlEncodeEntities(outputBuffer,
outputLengthBytes,
inputBytes,
inputLengthBytes,
quoteCharacter.characterCode)
if result == 0 { // zero represents success
// Have we consumed the length of the input buffer
let consumed = inputLengthBytes.pointee
if consumed == inputLength {
loop = false
return Data(bytes: outputBuffer, count: Int(outputLengthBytes.pointee))
} else {
// if we have not consumed the full input buffer.
// estimate a new output buffer length
let ratio: Double
if inputLength == 0 {
ratio = 0.0
} else {
ratio = Double(consumed) / Double(inputLength)
}
outputLength = Int( (2.0 - ratio) * Double(outputLength) * bufferGrowthFactor )
}
} else {
loop = false
}
return nil
}
}
/**
Encodes the HTML entities within the receiver. This method interperates the receiver Data
instance as UTF-8 encoded string data. The returns the resulting UTF-8 encoded string with
the HTML entities encoded or nil if an error occurred.
- parameter quoteCharacter: The HTML quote character for escaping.
- returns: UTF-8 encoded data instance representing the encoded string, or nil if an error occurred.
*/
public func encodeHTMLEntities(quoteCharacter: HTMLQuoteCharacter = .doubleQuote) -> Data? {
let bufferGrowthFactor = 1.4
let inputLength = self.count
var outputLength = Int(Double(inputLength) * bufferGrowthFactor)
var inputLengthBytes = UnsafeMutablePointer<CInt>.allocate(capacity: 1)
var outputLengthBytes = UnsafeMutablePointer<CInt>.allocate(capacity: 1)
defer {
inputLengthBytes.deallocate(capacity: 1)
outputLengthBytes.deallocate(capacity: 1)
}
var loop = true
repeat {
inputLengthBytes.pointee = CInt(inputLength)
outputLengthBytes.pointee = CInt(outputLength)
let outputData = encodeHTMLEntitiesBytes(&outputLength,
outputLengthBytes,
inputLengthBytes,
quoteCharacter,
inputLength,
&loop,
bufferGrowthFactor)
if let outputData = outputData {
return outputData
}
} while loop
return nil
}
}
public extension String {
/**
Encodes the HTML entities within the receiver.
- parameter quoteCharacter: The HTML quote character for escaping.
- returns: The encoded string, or nil if an error occurred.
*/
public func encodeHTMLEntities(quoteCharacter: HTMLQuoteCharacter = .doubleQuote) -> String? {
let utf8Data = Data(self.utf8)
guard let encoded = utf8Data.encodeHTMLEntities(quoteCharacter: quoteCharacter) else {
return nil
}
return String(data: encoded, encoding: .utf8)
}
}
| apache-2.0 | f89875cf3b6f1a8fdd6813a72b8bec73 | 37.337838 | 105 | 0.5497 | 5.662675 | false | false | false | false |
MitchellPhillips22/TIY-Assignments | Day 1/Swift101 Asssignment.playground/Pages/Control Flow.xcplaygroundpage/Contents.swift | 1 | 5276 | //: ## Control Flow
//:
//: Swift has two types of control flow statements. _Conditional statements_, like `if` and `switch`, check whether a condition is true—that is, if its value evaluates to the Boolean `true`—before executing a piece of code. _Loops_, like `for`-`in` and `while`, execute the same piece of code multiple times.
//:
//: An `if` statement checks whether a certain condition is true, and if it is, the `if` statement evaluates the code inside the statement. You can add an `else` clause to an `if` statement to define more complex behavior. An `else` clause can be used to chain `if` statements together, or it can stand on its own, in which case the `else` clause is executed if none of the chained `if` statements evaluate to `true`.
//:
let number = 600
if number < 10 {
print("The number is small")
} else if number > 100 {
print("The number is pretty big")
} else {
print("The number is between 10 and 100")
}
//: > **Experiment**:
//: > Change `number` to a different integer value to see how that affects which line prints.
//:
//: Statements can be nested to create complex, interesting behavior in a program. Here’s an example of an `if` statement with an `else` clause nested inside a `for`-`in` statement (which iterates through each item in a collection in order, one-by-one).
//:
let individualScores = [75, 43, 103, 87, 12]
var teamScore = 0
for score in individualScores {
if score > 50 {
teamScore += 3
} else {
teamScore += 1
}
}
print(teamScore)
//: Use _optional binding_ in an `if` statement to check whether an optional contains a value.
//:
var optionalName: String? = nil
var greeting = "Hello!"
if let name = optionalName {
greeting = "Hello, \(name)"
} else {
greeting = "Good Morning."
}
//: > **Experiment**:
//: > Change `optionalName` to `nil`. What greeting do you get? Add an `else` clause that sets a different greeting if `optionalName` is `nil`.
//:
//: If the optional value is `nil`, the conditional is `false`, and the code in braces is skipped. Otherwise, the optional value is unwrapped and assigned to the constant after `let`, which makes the unwrapped value available inside the block of code.
//:
//: You can use a single `if` statement to bind multiple values. A `where` clause can be added to a case to further scope the conditional statement. In this case, the `if` statement executes only if the binding is successful for all of these values and all conditions are met.
//:
var optionalHello: String? = "Hello"
if let hello = optionalHello where hello.hasPrefix("H"), let name = optionalName {
greeting = "\(hello), \(name)"
}
//: Switches in Swift are quite powerful. A `switch` statement supports any kind of data and a wide variety of comparison operations—it isn’t limited to integers and tests for equality. In this example, the `switch` statement switches on the value of the `vegetable` string, comparing the value to each of its cases and executing the one that matches.
//:
let vegetable = "red pepper"
switch vegetable {
case "celery":
let vegetableComment = "Add some raisins and make ants on a log."
case "cucumber", "watercress":
let vegetableComment = "That would make a good tea sandwich."
case let x where x.hasSuffix("pepper"):
let vegetableComment = "Is it a spicy \(x)?"
default:
let vegetableComment = "Everything tastes good in soup."
}
//: > **Experiment**:
//: > Try removing the default case. What error do you get?
//:
//: Notice how `let` can be used in a pattern to assign the value that matched that part of a pattern to a constant. Just like in an `if` statement, a `where` clause can be added to a case to further scope the conditional statement. However, unlike in an `if` statement, a switch case that has multiple conditions separated by commas executes when any of the conditions are met.
//:
//: After executing the code inside the switch case that matched, the program exits from the `switch` statement. Execution doesn’t continue to the next case, so you don’t need to explicitly break out of the `switch` statement at the end of each case’s code.
//:
//: Switch statements must be exhaustive. A default case is required, unless it’s clear from the context that every possible case is satisfied, such as when the switch statement is switching on an enumeration. This requirement ensures that one of the switch cases always executes.
//:
//: You can keep an index in a loop by using a `Range`. Use the _half-open range operator_ ( `..<`) to make a range of indexes.
//:
var firstForLoop = 0
for i in 0..<4 {
firstForLoop += i
}
print(firstForLoop)
//: The half-open range operator (`..<`) doesn’t include the upper number, so this range goes from `0` to `3` for a total of four loop iterations. Use the _closed range operator_ ( `...`) to make a range that includes both values.
//:
var secondForLoop = 0
for _ in 0...4 {
secondForLoop += 1
}
print(secondForLoop)
//: This range goes from `0` to `4` for a total of five loop iterations. The _underscore_ (`_`) represents a wildcard, which you can use when you don’t need to know which iteration of the loop is currently executing.
//:
//: [Previous](@previous) | [Next](@next)
| cc0-1.0 | 2e053fe0ce4b55ec4b8da1927fd176f0 | 54.305263 | 417 | 0.710316 | 4.082362 | false | false | false | false |
Friend-LGA/LGSideMenuController | LGSideMenuController/Extensions/Validators/LGSideMenuController+ValidatingViewsVisibility.swift | 1 | 3678 | //
// LGSideMenuController+ValidatingViewsVisibility.swift
// LGSideMenuController
//
//
// The MIT License (MIT)
//
// Copyright © 2015 Grigorii Lutkov <[email protected]>
// (https://github.com/Friend-LGA/LGSideMenuController)
//
// 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
import UIKit
internal extension LGSideMenuController {
func validateViewsVisibility() {
self.validateRootViewsVisibility()
self.validateLeftViewsVisibility()
self.validateRightViewsVisibility()
}
func validateRootViewsVisibility() {
guard self.shouldUpdateVisibility == true,
let backgroundDecorationView = self.rootViewBackgroundDecorationView,
let coverView = self.rootViewCoverView else { return }
backgroundDecorationView.isHidden = self.isRootViewShowing && !self.isLeftViewAlwaysVisible && !self.isRightViewAlwaysVisible
coverView.isHidden = self.isRootViewShowing
}
func validateLeftViewsVisibility() {
guard self.shouldUpdateVisibility == true,
let containerView = self.leftContainerView,
let coverView = self.leftViewCoverView,
let statusBarBackgroundView = self.leftViewStatusBarBackgroundView else { return }
containerView.isHidden = !self.isLeftViewVisibleToUser
coverView.isHidden = self.isLeftViewShowing || (self.isLeftViewAlwaysVisible && !self.isRightViewVisible)
statusBarBackgroundView.isHidden =
self.isLeftViewStatusBarBackgroundHidden ||
self.isLeftViewStatusBarHidden ||
self.isNavigationBarVisible() ||
!self.isViewLocatedUnderStatusBar
}
func validateRightViewsVisibility() {
guard self.shouldUpdateVisibility == true,
let containerView = self.rightContainerView,
let coverView = self.rightViewCoverView,
let statusBarBackgroundView = self.rightViewStatusBarBackgroundView else { return }
containerView.isHidden = !self.isRightViewVisibleToUser
coverView.isHidden = self.isRightViewShowing || (self.isRightViewAlwaysVisible && !self.isLeftViewVisible)
statusBarBackgroundView.isHidden =
self.isRightViewStatusBarBackgroundHidden ||
self.isRightViewStatusBarHidden ||
self.isNavigationBarVisible() ||
!self.isViewLocatedUnderStatusBar
}
private func isNavigationBarVisible() -> Bool {
guard let navigationController = navigationController else { return false }
return !navigationController.isNavigationBarHidden
}
}
| mit | d2c93a519ab1810a10934422f59aeda6 | 41.264368 | 133 | 0.721512 | 5.016371 | false | false | false | false |
bradhilton/SwiftTable | SwiftTable/Section/MultiSection+Implementation.swift | 1 | 4855 | //
// MultiSection+Implementation.swift
// SwiftTable
//
// Created by Bradley Hilton on 9/13/16.
// Copyright © 2016 Brad Hilton. All rights reserved.
//
extension MultiSection {
// Delegate
public func willDisplayCell(_ cell: UITableViewCell, forRow row: Int) {
delegate(row) { $0.willDisplayCell(cell, forRow: $1) }
}
public func didEndDisplayingCell(_ cell: UITableViewCell, forRow row: Int) {
delegate(row) { $0.didEndDisplayingCell(cell, forRow: $1) }
}
public func didEndDisplayingHeaderView(_ view: UIView) {}
public func didEndDisplayingFooterView(_ view: UIView) {}
public func heightForRow(_ row: Int) -> CGFloat {
return delegate(row) { $0.heightForRow($1) } ?? _table._parent.rowHeight
}
public func estimatedHeightForRow(_ row: Int) -> CGFloat {
return delegate(row) { $0.estimatedHeightForRow($1) } ?? _table._parent.estimatedRowHeight
}
public func accessoryButtonTappedForRow(_ row: Int) {
delegate(row) { $0.accessoryButtonTappedForRow($1) }
}
public func shouldHighlightRow(_ row: Int) -> Bool {
return delegate(row) { $0.shouldHighlightRow($1) } ?? true
}
public func didHighlightRow(_ row: Int) {
delegate(row) { $0.didHighlightRow($1) }
}
public func didUnhighlightRow(_ row: Int) {
delegate(row) { $0.didUnhighlightRow($1) }
}
public func willSelectRow(_ row: Int) -> Int? {
guard let section = sectionForRow(row),
let relativeRow = section.willSelectRow(rowForSection(section, row: row)) else {
return row
}
return rowFromSection(section, row: relativeRow)
}
public func willDeselectRow(_ row: Int) -> Int? {
guard let section = sectionForRow(row),
let relativeRow = section.willDeselectRow(rowForSection(section, row: row)) else {
return row
}
return rowFromSection(section, row: relativeRow)
}
public func didSelectRow(_ row: Int) {
delegate(row) { $0.didSelectRow($1) }
}
public func didDeselectRow(_ row: Int) {
delegate(row) { $0.didDeselectRow($1) }
}
public func editingStyleForRow(_ row: Int) -> UITableViewCell.EditingStyle {
return delegate(row) { $0.editingStyleForRow($1) } ?? .none
}
public func titleForDeleteConfirmationButtonForRow(_ row: Int) -> String? {
return delegate(row) { $0.titleForDeleteConfirmationButtonForRow($1) }
}
public func editActionsForRow(_ row: Int) -> [UITableViewRowAction]? {
return delegate(row) { $0.editActionsForRow($1) }
}
public func shouldIndentWhileEditingRow(_ row: Int) -> Bool {
return delegate(row) { $0.shouldIndentWhileEditingRow($1) } ?? true
}
public func willBeginEditingRow(_ row: Int) {
delegate(row) { $0.willBeginEditingRow($1) }
}
public func didEndEditingRow(_ row: Int?) {
guard let row = row else { return }
delegate(row) { $0.didEndEditingRow($1) }
}
public func targetRowForMoveFromRow(_ sourceRow: Int, toProposedRow proposedDestinationRow: Int) -> Int {
guard let source = sectionForRow(sourceRow), source === sectionForRow(proposedDestinationRow) else { return sourceRow }
return rowFromSection(source, row: source.targetRowForMoveFromRow(rowForSection(source, row: sourceRow), toProposedRow: rowForSection(source, row: proposedDestinationRow)))
}
public func indentationLevelForRow(_ row: Int) -> Int {
return delegate(row) { $0.indentationLevelForRow($1) } ?? 0
}
public func shouldShowMenuForRow(_ row: Int) -> Bool {
return delegate(row) { $0.shouldShowMenuForRow($1) } ?? false
}
// Data Source
public var numberOfRows: Int {
return sections.reduce(0) { $0 + $1.numberOfRows }
}
public func cellForRow(_ row: Int) -> UITableViewCell {
return delegate(row) { $0.cellForRow($1) } ?? UITableViewCell()
}
public func canEditRow(_ row: Int) -> Bool {
return delegate(row) { $0.canEditRow($1) } ?? false
}
public func canMoveRow(_ row: Int) -> Bool {
return delegate(row) { $0.canMoveRow($1) } ?? false
}
public func commitEditingStyle(_ editingStyle: UITableViewCell.EditingStyle, forRow row: Int) {
delegate(row) { $0.commitEditingStyle(editingStyle, forRow: $1) }
}
public func moveRow(_ sourceRow: Int, toRow destinationRow: Int) {
if let source = sectionForRow(sourceRow), source === sectionForRow(destinationRow) {
source.moveRow(rowForSection(source, row: sourceRow), toRow: rowForSection(source, row: destinationRow))
}
}
}
| mit | 2b209a5e270fdce19d5d9d9af48b6ff0 | 34.173913 | 180 | 0.627112 | 4.314667 | false | false | false | false |
overtake/TelegramSwift | Telegram-Mac/CancelResetAccountController.swift | 1 | 11989 | //
// CancelResetAccountController.swift
// Telegram
//
// Created by Mikhail Filimonov on 25/12/2018.
// Copyright © 2018 Telegram. All rights reserved.
//
import Cocoa
import Cocoa
import TGUIKit
import SwiftSignalKit
import TelegramCore
private let _id_input_code = InputDataIdentifier("_id_input_code")
private struct CancelResetAccountState : Equatable {
let code: String
let error: InputDataValueError?
let checking: Bool
let limit: Int32
init(code: String, error: InputDataValueError?, checking: Bool, limit: Int32) {
self.code = code
self.error = error
self.checking = checking
self.limit = limit
}
func withUpdatedCode(_ code: String) -> CancelResetAccountState {
return CancelResetAccountState(code: code, error: self.error, checking: self.checking, limit: self.limit)
}
func withUpdatedError(_ error: InputDataValueError?) -> CancelResetAccountState {
return CancelResetAccountState(code: self.code, error: error, checking: self.checking, limit: self.limit)
}
func withUpdatedChecking(_ checking: Bool) -> CancelResetAccountState {
return CancelResetAccountState(code: self.code, error: self.error, checking: checking, limit: self.limit)
}
func withUpdatedCodeLimit(_ limit: Int32) -> CancelResetAccountState {
return CancelResetAccountState(code: self.code, error: self.error, checking: self.checking, limit: limit)
}
}
func authorizationNextOptionText(currentType: SentAuthorizationCodeType, nextType: AuthorizationCodeNextType?, timeout: Int32?) -> (current: String, next: String, codeLength: Int) {
var codeLength: Int = 255
var basic: String = ""
var nextText: String = ""
switch currentType {
case let .otherSession(length: length):
codeLength = Int(length)
basic = strings().loginEnterCodeFromApp
nextText = strings().loginSendSmsIfNotReceivedAppCode
case let .sms(length: length):
codeLength = Int(length)
basic = strings().loginJustSentSms
case let .call(length: length):
codeLength = Int(length)
basic = strings().loginPhoneCalledCode
default:
break
}
if let nextType = nextType {
if let timeout = timeout {
let timeout = Int(timeout)
let minutes = timeout / 60;
let sec = timeout % 60;
let secValue = sec > 9 ? "\(sec)" : "0\(sec)"
if timeout > 0 {
switch nextType {
case .call:
nextText = strings().loginWillCall(minutes, secValue)
break
case .sms:
nextText = strings().loginWillSendSms(minutes, secValue)
break
default:
break
}
} else {
switch nextType {
case .call:
basic = strings().loginPhoneCalledCode
nextText = strings().loginPhoneDialed
break
default:
break
}
}
} else {
nextText = strings().loginSendSmsIfNotReceivedAppCode
}
}
return (current: basic, next: nextText, codeLength: codeLength)
}
private func timeoutSignal(codeData: CancelAccountResetData) -> Signal<Int32?, NoError> {
if let _ = codeData.nextType, let timeout = codeData.timeout {
return Signal { subscriber in
let value = Atomic<Int32>(value: timeout)
subscriber.putNext(timeout)
let timer = SwiftSignalKit.Timer(timeout: 1.0, repeat: true, completion: {
subscriber.putNext(value.modify { value in
return max(0, value - 1)
})
}, queue: Queue.mainQueue())
timer.start()
return ActionDisposable {
timer.invalidate()
}
}
} else {
return .single(nil)
}
}
private func cancelResetAccountEntries(state: CancelResetAccountState, data: CancelAccountResetData, timeout: Int32?, phone: String) -> [InputDataEntry] {
var entries: [InputDataEntry] = []
var sectionId: Int32 = 0
var index:Int32 = 0
entries.append(.sectionId(sectionId, type: .normal))
sectionId += 1
//
entries.append(.input(sectionId: sectionId, index: index, value: .string(state.code), error: state.error, identifier: _id_input_code, mode: .plain, data: InputDataRowData(), placeholder: nil, inputPlaceholder: strings().twoStepAuthRecoveryCode, filter: {String($0.unicodeScalars.filter { CharacterSet.decimalDigits.contains($0)})}, limit: state.limit))
index += 1
var nextOptionText = ""
if let nextType = data.nextType {
nextOptionText += authorizationNextOptionText(currentType: data.type, nextType: nextType, timeout: timeout).next
}
let phoneNumber = phone.hasPrefix("+") ? phone : "+\(phone)"
let formattedNumber = formatPhoneNumber(phoneNumber)
var result = strings().cancelResetAccountTextSMS(formattedNumber)
if !nextOptionText.isEmpty {
result += "\n\n" + nextOptionText
}
entries.append(.desc(sectionId: sectionId, index: index, text: .plain(result), data: InputDataGeneralTextData()))
entries.append(.sectionId(sectionId, type: .normal))
sectionId += 1
return entries
}
func cancelResetAccountController(context: AccountContext, phone: String, data: CancelAccountResetData) -> InputDataModalController {
let initialState = CancelResetAccountState(code: "", error: nil, checking: false, limit: 255)
let statePromise = ValuePromise(initialState, ignoreRepeated: true)
let stateValue = Atomic(value: initialState)
let updateState: ((CancelResetAccountState) -> CancelResetAccountState) -> Void = { f in
statePromise.set(stateValue.modify (f))
}
let actionsDisposable = DisposableSet()
let updateCodeLimitDisposable = MetaDisposable()
actionsDisposable.add(updateCodeLimitDisposable)
let confirmPhoneDisposable = MetaDisposable()
actionsDisposable.add(confirmPhoneDisposable)
let nextTypeDisposable = MetaDisposable()
actionsDisposable.add(nextTypeDisposable)
let currentDataPromise = Promise<CancelAccountResetData>()
currentDataPromise.set(.single(data))
let timeout = Promise<Int32?>()
timeout.set(currentDataPromise.get() |> mapToSignal(timeoutSignal))
updateCodeLimitDisposable.set((currentDataPromise.get() |> deliverOnMainQueue).start(next: { data in
updateState { current in
var limit:Int32 = 255
switch data.type {
case let .call(length):
limit = length
case let .otherSession(length):
limit = length
case let .sms(length):
limit = length
default:
break
}
return current.withUpdatedCodeLimit(limit)
}
}))
var close: (() -> Void)? = nil
let checkCode: (String) -> InputDataValidation = { code in
return .fail(.doSomething { f in
let checking = stateValue.with {$0.checking}
let code = stateValue.with { $0.code }
updateState { current in
return current.withUpdatedChecking(true)
}
if !checking {
confirmPhoneDisposable.set(showModalProgress(signal: context.engine.auth.requestCancelAccountReset(phoneCodeHash: data.hash, phoneCode: code) |> deliverOnMainQueue, for: context.window).start(error: { error in
let errorText: String
switch error {
case .generic:
errorText = strings().twoStepAuthGenericError
case .invalidCode:
errorText = strings().twoStepAuthRecoveryCodeInvalid
case .codeExpired:
errorText = strings().twoStepAuthRecoveryCodeExpired
case .limitExceeded:
errorText = strings().twoStepAuthFloodError
}
updateState {
return $0.withUpdatedError(InputDataValueError(description: errorText, target: .data)).withUpdatedChecking(false)
}
f(.fail(.fields([_id_input_code : .shake])))
}, completed: {
updateState {
return $0.withUpdatedChecking(false)
}
close?()
alert(for: context.window, info: strings().cancelResetAccountSuccess(formatPhoneNumber(phone.hasPrefix("+") ? phone : "+\(phone)")))
}))
}
})
}
let signal = combineLatest(statePromise.get(), currentDataPromise.get(), timeout.get()) |> map { state, data, timeout in
return InputDataSignalValue(entries: cancelResetAccountEntries(state: state, data: data, timeout: timeout, phone: phone))
}
let resendCode = currentDataPromise.get()
|> mapToSignal { [weak currentDataPromise] data -> Signal<Void, NoError> in
if let _ = data.nextType {
return timeout.get()
|> filter { $0 == 0 }
|> take(1)
|> mapToSignal { _ -> Signal<Void, NoError> in
return Signal { subscriber in
return context.engine.auth.requestNextCancelAccountResetOption(phoneNumber: phone, phoneCodeHash: data.hash).start(next: { next in
currentDataPromise?.set(.single(next))
}, error: { error in
})
}
}
} else {
return .complete()
}
}
nextTypeDisposable.set(resendCode.start())
let controller = InputDataController(dataSignal: signal, title: strings().cancelResetAccountTitle, validateData: { data in
return checkCode(stateValue.with { $0.code })
}, updateDatas: { data in
updateState { current in
return current.withUpdatedCode(data[_id_input_code]?.stringValue ?? current.code).withUpdatedError(nil)
}
let codeLimit = stateValue.with { $0.limit }
let code = stateValue.with { $0.code }
if code.length == codeLimit {
return checkCode(code)
}
return .none
}, afterDisappear: {
actionsDisposable.dispose()
}, updateDoneValue: { data in
return { f in
let checking = stateValue.with { $0.checking }
f(checking ? .loading : .invisible)
}
}, hasDone: true)
controller.getBackgroundColor = {
theme.colors.background
}
let modalInteractions = ModalInteractions(acceptTitle: strings().modalSend, accept: { [weak controller] in
_ = controller?.returnKeyAction()
}, drawBorder: true, height: 50, singleButton: true)
let modalController = InputDataModalController(controller, modalInteractions: modalInteractions)
controller.leftModalHeader = ModalHeaderData(image: theme.icons.modalClose, handler: { [weak modalController] in
modalController?.close()
})
close = { [weak modalController] in
modalController?.modal?.close()
}
return modalController
}
| gpl-2.0 | 7ba94639e4e775951a9c7f273d420f9e | 35.217523 | 356 | 0.580414 | 5.109974 | false | false | false | false |
appnexus/mobile-sdk-ios | tests/TrackerUITest/UITestApp/UITestViewController.swift | 1 | 5933 | /* Copyright 2019 APPNEXUS 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 UITestViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
self.title = "UI Test Type"
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(true)
ANHTTPStubbingManager.shared().disable()
ANHTTPStubbingManager.shared().removeAllStubs()
ANStubManager.sharedInstance().enableStubbing()
ANStubManager.sharedInstance().disableStubbing()
let placementTestStoryboard = UIStoryboard(name: PlacementTestConstants.PlacementTest, bundle: nil)
if ProcessInfo.processInfo.arguments.contains(PlacementTestConstants.BannerAd.testRTBBanner320x50) || ProcessInfo.processInfo.arguments.contains(PlacementTestConstants.BannerAd.testRTBBanner300x250) {
let bannerAdViewController = placementTestStoryboard.instantiateViewController(withIdentifier: "BannerAdViewController") as! BannerAdViewController
self.navigationController?.pushViewController(bannerAdViewController, animated: true)
}
else if ProcessInfo.processInfo.arguments.contains(PlacementTestConstants.BannerNativeAd.testRTBBannerNative) || ProcessInfo.processInfo.arguments.contains(PlacementTestConstants.BannerNativeAd.testRTBBannerNativeRendering){
let bannerNativeAdViewController = placementTestStoryboard.instantiateViewController(withIdentifier: "BannerNativeAdViewController") as! BannerNativeAdViewController
self.navigationController?.pushViewController(bannerNativeAdViewController, animated: true)
}
else if ProcessInfo.processInfo.arguments.contains(PlacementTestConstants.BannerVideoAd.testBannerVideo) || ProcessInfo.processInfo.arguments.contains(PlacementTestConstants.BannerVideoAd.testVPAIDBannerVideo) {
let bannerVideoAdViewController = placementTestStoryboard.instantiateViewController(withIdentifier: "BannerVideoAdViewController") as! BannerVideoAdViewController
self.navigationController?.pushViewController(bannerVideoAdViewController, animated: true)
}
else if ProcessInfo.processInfo.arguments.contains(PlacementTestConstants.InterstitialAd.testRTBInterstitial) {
let interstitialAdViewController = placementTestStoryboard.instantiateViewController(withIdentifier: "InterstitialAdViewController") as! InterstitialAdViewController
self.navigationController?.pushViewController(interstitialAdViewController, animated: true)
}
else if ProcessInfo.processInfo.arguments.contains(PlacementTestConstants.NativeAd.testRTBNative) {
let nativeAdViewController = placementTestStoryboard.instantiateViewController(withIdentifier: "NativeAdViewController") as! NativeAdViewController
self.navigationController?.pushViewController(nativeAdViewController, animated: true)
}
else if ProcessInfo.processInfo.arguments.contains(PlacementTestConstants.VideoAd.testRTBVideo) || ProcessInfo.processInfo.arguments.contains(PlacementTestConstants.VideoAd.testVPAIDVideoAd){
let videoAdViewController = placementTestStoryboard.instantiateViewController(withIdentifier: "VideoAdViewController") as! VideoAdViewController
self.navigationController?.pushViewController(videoAdViewController, animated: true)
}
if ProcessInfo.processInfo.arguments.contains(BannerImpressionClickTrackerTest) || ProcessInfo.processInfo.arguments.contains(BannerNativeImpressionClickTrackerTest) || ProcessInfo.processInfo.arguments.contains(BannerNativeRendererImpressionClickTrackerTest) || ProcessInfo.processInfo.arguments.contains(BannerVideoImpressionClickTrackerTest) {
self.openViewController("BannerNativeVideoTrackerTestVC")
}
if ProcessInfo.processInfo.arguments.contains(InterstitialImpressionClickTrackerTest) {
self.openViewController("InterstitialAdTrackerTestVC")
} else if ProcessInfo.processInfo.arguments.contains(VideoImpressionClickTrackerTest) {
self.openViewController("VideoAdTrackerTestVC")
} else if ProcessInfo.processInfo.arguments.contains(NativeImpressionClickTrackerTest) {
self.openViewController("NativeAdTrackerTestVC")
}else if ProcessInfo.processInfo.arguments.contains(MARBannerImpressionClickTrackerTest) || ProcessInfo.processInfo.arguments.contains(MARNativeImpressionClickTrackerTest) || ProcessInfo.processInfo.arguments.contains(MARBannerNativeRendererImpressionClickTrackerTest) {
self.openViewController("MARBannerNativeRendererAdTrackerTestVC")
}
else if ProcessInfo.processInfo.arguments.contains(BannerImpression1PxTrackerTest) || ProcessInfo.processInfo.arguments.contains(NativeImpression1PxTrackerTest) {
self.openViewController("ScrollViewController")
}
}
func openViewController(_ viewController: String) {
let sb = UIStoryboard(name: viewController, bundle: nil)
let vc = sb.instantiateViewController(withIdentifier: viewController)
vc.modalPresentationStyle = .fullScreen
navigationController?.pushViewController(vc, animated: true)
}
}
| apache-2.0 | 9e44c0024bfd4e6ed0c189686e458e6c | 67.195402 | 354 | 0.766728 | 5.639734 | false | true | false | false |
oceanfive/swift | swift_two/swift_two/Classes/Model/HYStatuses.swift | 1 | 8794 | //
// HYStatuses.swift
// swift_two
//
// Created by ocean on 16/6/20.
// Copyright © 2016年 ocean. All rights reserved.
//
import UIKit
class HYStatuses: NSObject {
//字符串型的微博ID
var idstr: String?
//微博信息内容
var text: String?
//微博创建时间 -- Optional("Tue Jun 21 23:34:28 +0800 2016")
var created_at: String?{
didSet(oldValue){
//获取这条微博的日期
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "EEE MMM dd HH:mm:ss z yyyy"
let tempDate = dateFormatter.dateFromString(created_at!)
//获取当前日期
let currentDate = NSDate()
// print(currentDate.distanceDate(tempDate!))
// print("tempDate--\(tempDate!)")
// print("currentDate--\(currentDate)")
if ((tempDate?.isThisYear()) != nil) { //今年
if ((tempDate?.isToday()) != nil) { // 今天
let timeInterval = currentDate.distanceDate(tempDate!)
if timeInterval <= 60 { // 一分钟内 刚刚
created_at = "刚刚"
}else if timeInterval > 60 && timeInterval <= 60 * 60 { // 一个小时内 6分钟前
//MARK: - 格式化字符串, oc 和 swift相同,都需要使用 format,行不通???
let second = timeInterval / 60
created_at = "\(Int(second))分钟前"
}else { // 超过一个小时 2小时前
let hour = timeInterval / (60 * 60)
created_at = "\(Int(hour))小时前"
}
}else if ((tempDate?.isYesterday()) != nil){ // 昨天 昨天 20:12
let calendar = NSCalendar.currentCalendar()
// let unit = [.Minute, .Hour]
//MARK: - 这里注意oc和siwft日期分离元素的区别 oc | -- 多项选择 swift 结构体
let componets = calendar.components([.Hour , .Minute], fromDate: tempDate!)
created_at = "昨天 \(componets.hour):\(componets.minute)"
}else { // 06-20
let calendar = NSCalendar.currentCalendar()
let componets = calendar.components([.Month, .Day], fromDate: tempDate!)
created_at = "\(componets.month)-\(componets.day)"
}
}else {//不是今年 2015-09-20
let calendar = NSCalendar.currentCalendar()
let componets = calendar.components([.Year, .Month, .Day], fromDate: tempDate!)
created_at = "\(componets.year)-\(componets.month)-\(componets.day)"
}
}
}
//微博来源 -- Optional("<a href=\"http://app.weibo.com/t/feed/6vtZb0\" rel=\"nofollow\">微博 weibo.com</a>")
var source: String?{
//MARK: - 如果需要修改属性的值,需要在didSet方法中进行修改
// willSet(newValue){
//// print("newValue---\(newValue)")
////MARK: - 这里有时候来源为空,需要进行判断, 判断条件为 "" 不是 nil
// if newValue != "" {
//
// let sourceString = newValue as NSString
////MARK: - 这里swift设置失败,转为oc尝试!
// let rangeBegin = sourceString.rangeOfString(">")
//
// let rangeEnd = sourceString.rangeOfString("</")
//
//// print(rangeBegin)
////
//// print(rangeEnd)
// //MARK: - oc和swiftrange初始化对比
// // let range = NSMakeRange(rangeBegin?.startIndex as Int , (rangeEnd?.startIndex - rangeBegin?.startIndex) as Int)
// // let range = Range.init(start: rangeBegin?.startIndex, end: rangeEnd?.startIndex)
// let range = NSMakeRange(rangeBegin.location + 1, rangeEnd.location - rangeBegin.location - 1)
////MARK: - Attempting to store to property 'source' within its own willSet, which is about to be overwritten by the new value
// self.source = sourceString.substringWithRange(range)
//
//// print("self.source---\(self.source)")
//// print("source--\(source)")
// }
// }
didSet(oldValue){
if source != "" {
let sourceString = source! as NSString
//MARK: - 这里swift设置失败,转为oc尝试!
let rangeBegin = sourceString.rangeOfString(">")
let rangeEnd = sourceString.rangeOfString("</")
// print(rangeBegin)
//
// print(rangeEnd)
//MARK: - oc和swiftrange初始化对比
// let range = NSMakeRange(rangeBegin?.startIndex as Int , (rangeEnd?.startIndex - rangeBegin?.startIndex) as Int)
// let range = Range.init(start: rangeBegin?.startIndex, end: rangeEnd?.startIndex)
let range = NSMakeRange(rangeBegin.location + 1, rangeEnd.location - rangeBegin.location - 1)
//MARK: - Attempting to store to property 'source' within its own willSet, which is about to be overwritten by the new value
self.source = sourceString.substringWithRange(range)
// print("self.source---\(self.source)")
// print("source--\(source)")
}
// print(source)
// print("oldValue---\(oldValue)")
}
}
//MARK: - 这里会崩溃,存储属性使用了get,set,xcode崩溃
// {
//
// set(newValue) {
//
// let sourceString = newValue
//
// let rangeBegin = sourceString.rangeOfString(">")
//
// let rangeEnd = sourceString.rangeOfString("</")
////MARK: - oc和swiftrange初始化对比
//// let range = NSMakeRange(rangeBegin?.startIndex as Int , (rangeEnd?.startIndex - rangeBegin?.startIndex) as Int)
//// let range = Range.init(start: rangeBegin?.startIndex, end: rangeEnd?.startIndex)
// let range = Range(start: rangeBegin?.startIndex as! Int, end: rangeEnd?.startIndex as! Int)
//
// self.source = sourceString.su
//
// }
//
// }
//MARK: - 记住!所有的存储属性都是要给定初始值的,对于类的话初始值就是在这个类之后加上一个问号
//微博作者的用户信息字段 详细
var user: HYUser?
//被转发的原微博信息字段,当该微博为转发微博时返回 详细
var retweeted_status: HYStatuses?
// var retweeted_status = HYStatuses.self
//转发数
var reposts_count: Int?
//评论数
var comments_count: Int?
//表态数
var attitudes_count: Int?
//微博配图地址,多图时返回多图链接。无配图返回“[]” 数组里面都是HYPhoto模型
var pic_urls: [AnyObject] = []
//MARK: - 告诉这个模型中,哪个属性又是一个模型
override static func mj_objectClassInArray() -> [NSObject : AnyObject]! {
return ["pic_urls": HYPhoto.classForCoder()]
}
// func statusesWithDict(dict: [String : AnyObject]) -> HYStatuses {
//
// let model = HYStatuses()
//
// model.created_at = dict["created_at"] as? String
// model.idstr = dict["idstr"] as? String
// model.text = dict["text"] as? String
// model.source = dict["source"] as? String
// model.reposts_count = dict["reposts_count"] as? Int
// model.comments_count = dict["comments_count"] as? Int
// model.attitudes_count = dict["attitudes_count"] as? Int
//
//
// model.user = HYUser().userWithDict((dict["user"] as? [String: String])!)
//// model.retweeted_status =
//
//// let tempDict = dict["pic_urls"] as? Array
////
//// model.pic_urls[0] = HYPhoto().photoWithDict(tempDict[0])
//
// return model
//
//
// }
}
| mit | 48fa8cda24190ecba20290d817be22ca | 34.449339 | 143 | 0.488008 | 4.345032 | false | false | false | false |
OrRon/NexmiiHack | Pods/Dwifft/Dwifft/Dwifft+UIKit.swift | 1 | 3294 | //
// TableViewDiffCalculator.swift
// Dwifft
//
// Created by Jack Flintermann on 3/13/15.
// Copyright (c) 2015 Places. All rights reserved.
//
#if os(iOS)
import UIKit
open class TableViewDiffCalculator<T: Equatable> {
open weak var tableView: UITableView?
public init(tableView: UITableView, initialRows: [T] = []) {
self.tableView = tableView
self.rows = initialRows
}
/// Right now this only works on a single section of a tableView. If your tableView has multiple sections, though, you can just use multiple TableViewDiffCalculators, one per section, and set this value appropriately on each one.
open var sectionIndex: Int = 0
/// You can change insertion/deletion animations like this! Fade works well. So does Top/Bottom. Left/Right/Middle are a little weird, but hey, do your thing.
open var insertionAnimation = UITableViewRowAnimation.automatic, deletionAnimation = UITableViewRowAnimation.automatic
/// Change this value to trigger animations on the table view.
open var rows : [T] {
didSet {
let oldRows = oldValue
let newRows = self.rows
let diff = oldRows.diff(newRows)
if (diff.results.count > 0) {
tableView?.beginUpdates()
let insertionIndexPaths = diff.insertions.map({ IndexPath(row: $0.idx, section: self.sectionIndex) })
let deletionIndexPaths = diff.deletions.map({ IndexPath(row: $0.idx, section: self.sectionIndex) })
tableView?.insertRows(at: insertionIndexPaths, with: insertionAnimation)
tableView?.deleteRows(at: deletionIndexPaths, with: deletionAnimation)
tableView?.endUpdates()
}
}
}
}
open class CollectionViewDiffCalculator<T: Equatable> {
open weak var collectionView: UICollectionView?
public init(collectionView: UICollectionView, initialRows: [T] = []) {
self.collectionView = collectionView
self.rows = initialRows
}
/// Right now this only works on a single section of a collectionView. If your collectionView has multiple sections, though, you can just use multiple CollectionViewDiffCalculators, one per section, and set this value appropriately on each one.
open var sectionIndex: Int = 0
/// Change this value to trigger animations on the collection view.
open var rows : [T] {
didSet {
let oldRows = oldValue
let newRows = self.rows
let diff = oldRows.diff(newRows)
if (diff.results.count > 0) {
let insertionIndexPaths = diff.insertions.map({ IndexPath(item: $0.idx, section: self.sectionIndex) })
let deletionIndexPaths = diff.deletions.map({ IndexPath(item: $0.idx, section: self.sectionIndex) })
collectionView?.performBatchUpdates({ () -> Void in
self.collectionView?.insertItems(at: insertionIndexPaths)
self.collectionView?.deleteItems(at: deletionIndexPaths)
}, completion: nil)
}
}
}
}
#endif
| mit | 5ed95b4da24d9cba406dfef539e854aa | 37.302326 | 248 | 0.62204 | 4.983359 | false | false | false | false |
pksprojects/ElasticSwift | Sources/ElasticSwift/Requests/DeleteRequest.swift | 1 | 3784 | //
// DeleteRequest.swift
// ElasticSwift
//
// Created by Prafull Kumar Soni on 5/31/17.
//
//
import ElasticSwiftCore
import Foundation
import NIOHTTP1
// MARK: - Delete Request Builder
public class DeleteRequestBuilder: RequestBuilder {
public typealias RequestType = DeleteRequest
private var _index: String?
private var _type: String?
private var _id: String?
private var _version: String?
private var _versionType: VersionType?
private var _refresh: IndexRefresh?
public init() {}
@discardableResult
public func set(index: String) -> Self {
_index = index
return self
}
@discardableResult
@available(*, deprecated, message: "Elasticsearch has deprecated use of custom types and will be remove in 7.0")
public func set(type: String) -> Self {
_type = type
return self
}
@discardableResult
public func set(id: String) -> Self {
_id = id
return self
}
@discardableResult
public func set(version: String) -> Self {
_version = version
return self
}
@discardableResult
public func set(versionType: VersionType) -> Self {
_versionType = versionType
return self
}
@discardableResult
public func set(refresh: IndexRefresh) -> Self {
_refresh = refresh
return self
}
public var index: String? {
return _index
}
public var type: String? {
return _type
}
public var id: String? {
return _id
}
public var version: String? {
return _version
}
public var versionType: VersionType? {
return _versionType
}
public var refresh: IndexRefresh? {
return _refresh
}
public func build() throws -> RequestType {
return try DeleteRequest(withBuilder: self)
}
}
// MARK: - Delete Request
public struct DeleteRequest: Request, BulkableRequest {
public var headers = HTTPHeaders()
public let index: String
public let type: String
public let id: String
public var version: String?
public var versionType: VersionType?
public var refresh: IndexRefresh?
public init(index: String, type: String = "_doc", id: String) {
self.index = index
self.type = type
self.id = id
}
internal init(withBuilder builder: DeleteRequestBuilder) throws {
guard builder.index != nil else {
throw RequestBuilderError.missingRequiredField("index")
}
guard builder.id != nil else {
throw RequestBuilderError.missingRequiredField("id")
}
self.init(index: builder.index!, type: builder.type ?? "_doc", id: builder.id!)
version = builder.version
versionType = builder.versionType
refresh = builder.refresh
}
public var method: HTTPMethod {
return .DELETE
}
public var endPoint: String {
return index + "/" + type + "/" + id
}
public var queryParams: [URLQueryItem] {
var params = [URLQueryItem]()
if let version = self.version, let versionType = self.versionType {
params.append(URLQueryItem(name: QueryParams.version.rawValue, value: version))
params.append(URLQueryItem(name: QueryParams.versionType.rawValue, value: versionType.rawValue))
}
if let refresh = self.refresh {
params.append(URLQueryItem(name: QueryParams.refresh.rawValue, value: refresh.rawValue))
}
return params
}
public func makeBody(_: Serializer) -> Result<Data, MakeBodyError> {
return .failure(.noBodyForRequest)
}
public var opType: OpType {
return .delete
}
}
extension DeleteRequest: Equatable {}
| mit | 38d10086d6b710c7d5c7dfb7b0ee4e98 | 23.412903 | 116 | 0.625529 | 4.586667 | false | false | false | false |
MidnightPulse/Tabman | Sources/Tabman/TabmanBar/Transitioning/IndicatorTransition/TabmanScrollingBarIndicatorTransition.swift | 3 | 5638 | //
// TabmanScrollingBarIndicatorTransition.swift
// Tabman
//
// Created by Merrick Sapsford on 14/03/2017.
// Copyright © 2017 Merrick Sapsford. All rights reserved.
//
import UIKit
import Pageboy
/// Transition for updating a scrolling bar.
/// Handles keeping indicator centred and scrolling for item visibility.
internal class TabmanScrollingBarIndicatorTransition: TabmanIndicatorTransition {
override func transition(withPosition position: CGFloat,
direction: PageboyViewController.NavigationDirection,
indexRange: Range<Int>,
bounds: CGRect) {
guard let scrollingButtonBar = self.tabmanBar as? TabmanScrollingButtonBar else { return }
let (lowerIndex, upperIndex) = TabmanPositionalUtil.lowerAndUpperIndex(forPosition: position,
minimum: indexRange.lowerBound,
maximum: indexRange.upperBound)
let lowerButton = scrollingButtonBar.buttons[lowerIndex]
let upperButton = scrollingButtonBar.buttons[upperIndex]
var integral: Float = 0.0
let transitionProgress = CGFloat(modff(Float(position), &integral))
self.updateIndicator(forTransitionProgress: transitionProgress,
in: scrollingButtonBar,
lowerButton: lowerButton,
upperButton: upperButton)
self.scrollIndicatorPositionToVisible(in: scrollingButtonBar)
}
override func updateForCurrentPosition() {
guard let scrollingButtonBar = self.tabmanBar as? TabmanScrollingButtonBar else { return }
self.scrollIndicatorPositionToVisible(in: scrollingButtonBar)
}
// MARK: Updating
private func updateIndicator(forTransitionProgress progress: CGFloat,
in bar: TabmanScrollingButtonBar,
lowerButton: UIButton,
upperButton: UIButton) {
if bar.indicatorIsProgressive {
let indicatorStartFrame = lowerButton.frame.origin.x + lowerButton.frame.size.width
let indicatorEndFrame = upperButton.frame.origin.x + upperButton.frame.size.width
let endFrameDiff = indicatorEndFrame - indicatorStartFrame
bar.indicatorWidth?.constant = indicatorStartFrame + (endFrameDiff * progress)
guard bar.indicatorBounces || bar.indicatorCompresses else { return }
if (lowerButton === upperButton) {
let indicatorWidth = bar.indicatorWidth?.constant ?? 0.0
bar.indicatorWidth?.constant = indicatorWidth + (indicatorWidth * progress)
}
} else {
let widthDiff = (upperButton.frame.size.width - lowerButton.frame.size.width) * progress
let interpolatedWidth = lowerButton.frame.size.width + widthDiff
bar.indicatorWidth?.constant = interpolatedWidth
let xDiff = (upperButton.frame.origin.x - lowerButton.frame.origin.x) * progress
let interpolatedXOrigin = lowerButton.frame.origin.x + xDiff
bar.indicatorLeftMargin?.constant = interpolatedXOrigin
let isOutOfBounds = lowerButton === upperButton
// compress indicator at boundaries if required
if bar.indicatorCompresses && isOutOfBounds {
let indicatorWidth = bar.indicatorWidth?.constant ?? 0.0
let indicatorDiff = (indicatorWidth * fabs(progress))
bar.indicatorWidth?.constant = indicatorWidth - indicatorDiff
if progress > 0.0 {
let indicatorLeftMargin = bar.indicatorLeftMargin?.constant ?? 0.0
bar.indicatorLeftMargin?.constant = indicatorLeftMargin + indicatorDiff
}
}
// bounce indicator at boundaries if required
if bar.indicatorBounces && isOutOfBounds {
let indicatorWidth = bar.indicatorWidth?.constant ?? 0.0
bar.indicatorLeftMargin?.constant = (bar.indicatorLeftMargin?.constant ?? 0.0) + (indicatorWidth * progress)
}
}
}
private func scrollIndicatorPositionToVisible(in bar: TabmanScrollingButtonBar) {
var offset: CGFloat = 0.0
let maxOffset = bar.scrollView.contentSize.width - bar.bounds.size.width
if bar.indicatorIsProgressive {
let index = Int(ceil(bar.currentPosition))
guard bar.buttons.count > index else {
return
}
let buttonFrame = bar.buttons[index].frame
offset = ((bar.indicatorWidth?.constant ?? 0.0) - (bar.bounds.size.width / 2.0)) - (buttonFrame.size.width / 2.0)
} else {
let indicatorXOffset = bar.indicatorLeftMargin?.constant ?? 0.0
let indicatorWidthOffset = (bar.bounds.size.width - (bar.indicatorWidth?.constant ?? 0)) / 2.0
guard indicatorWidthOffset > 0.0 else {
return
}
offset = indicatorXOffset - indicatorWidthOffset
}
offset = max(0.0, min(maxOffset, offset))
bar.scrollView.contentOffset = CGPoint(x: offset, y: 0.0)
}
}
| mit | 2c53b9ab9c0843246e07e4efff74ae05 | 43.385827 | 125 | 0.588079 | 5.631369 | false | false | false | false |
alexwinston/UIViewprint | UIViewprint/ViewController9.swift | 1 | 4168 | //
// ViewController9.swift
// Blueprint
//
// Created by Alex Winston on 2/9/16.
// Copyright © 2016 Alex Winston. All rights reserved.
//
import Foundation
import UIKit
infix operator < { associativity left }
class ViewController9: UIViewableController,UIScrollViewDelegate {
let scrollView = UIScrollView()
var colors:[UIColor] = [UIColor.redColor(), UIColor.orangeColor(), UIColor.greenColor(), UIColor.yellowColor()]
var frame: CGRect = CGRectMake(0, 0, 0, 0)
var pageControl : UIPageControl = UIPageControl(frame: CGRectMake(50, 300, 200, 50))
var views:[UIView] = []
override func viewDidLoad() {
super.viewDidLoad()
self.title = "Example 8"
self.edgesForExtendedLayout = UIRectEdge.None;
self.scrollView.frame = self.view.frame
let view1 = UIViewable(style:UIViewableStyle(display:.Inline))
// < .view+>
< "Test 1">>
// < .view/>
self.views.append(view1)
let view2 = UIViewable(style:UIViewableStyle(display:.Flex(.Column)))
// < .view+>
< "Test 2a"==.display(.Block)>>
< "Test 2b"==.display(.Block)>>
// < .view/>
self.views.append(view2)
let view3 = UIViewable(style:UIViewableStyle(display:.Flex(.Column)))
< .view+>
< "Test 3a">>
< "Test 3b">>
< .view/>
self.views.append(view3)
self.scrollView.pagingEnabled = true
self.scrollView.delegate = self
self.view.addSubview(scrollView)
for index in 0..<views.count {
let subView = views[index]
subView.frame.origin.x = self.scrollView.frame.size.width * CGFloat(index)
subView.backgroundColor = colors[index]
self.scrollView.addSubview(subView)
}
self.scrollView.contentSize = CGSizeMake(self.scrollView.frame.size.width * CGFloat(views.count), self.scrollView.frame.size.height)
configurePageControl()
pageControl.addTarget(self, action: Selector("changePage:"), forControlEvents: UIControlEvents.ValueChanged)
}
func configurePageControl() {
// The total number of pages that are available is based on how many views were added.
self.pageControl.numberOfPages = views.count
self.pageControl.currentPage = 0
self.pageControl.tintColor = UIColor.redColor()
self.pageControl.pageIndicatorTintColor = UIColor.blackColor()
self.pageControl.currentPageIndicatorTintColor = UIColor.greenColor()
self.view.addSubview(pageControl)
}
// MARK : TO CHANGE WHILE CLICKING ON PAGE CONTROL
func changePage(sender: AnyObject) -> () {
let x = CGFloat(pageControl.currentPage) * scrollView.frame.size.width
scrollView.setContentOffset(CGPointMake(x, 0), animated: true)
}
func scrollViewDidEndDecelerating(scrollView: UIScrollView) {
let pageNumber = round(scrollView.contentOffset.x / scrollView.frame.size.width)
pageControl.currentPage = Int(pageNumber)
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
var contentRect = CGRectZero;
for subview in self.scrollView.subviews {
contentRect = CGRectUnion(contentRect, subview.frame);
}
self.scrollView.contentSize = contentRect.size;
}
override func viewWillTransitionToSize(size: CGSize, withTransitionCoordinator coordinator: UIViewControllerTransitionCoordinator) {
super.viewWillTransitionToSize(size, withTransitionCoordinator: coordinator)
// self.view.frame.size = size
self.scrollView.frame.size = size
for subview in self.view.subviews {
subview.layoutSubviews()
}
self.debugSubviews(self.view, indent: "")
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
} | mit | fa8e1b9baf6a7266638ed9122f0bebcc | 34.931034 | 140 | 0.62707 | 4.86231 | false | false | false | false |
ShiWeiCN/Goku | Goku/Source/Alert/AlertTheme.swift | 1 | 8215 | // AlertTheme.swift
// Goku (https://github.com/ShiWeiCN/Goku)
//
//
// Copyright (c) 2017 shiwei (http://shiweicn.github.io/)
//
// 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(iOS)
import UIKit
#endif
public typealias CornerRadius = CGFloat
// Alert view & Action Sheet Background view's shape
public enum AlertShape {
case squared
case rounded(CornerRadius)
var cornerRadius: CornerRadius {
get {
switch self {
case .squared: return 0.0
case .rounded(let cornerRadius): return cornerRadius
}
}
}
}
public enum AlertOverlay {
case normal(UIColor)
case blurEffect(UIBlurEffectStyle)
}
public class AlertTheme {
//
public typealias Font = UIFont
public typealias Color = UIColor
// MARK: Private
fileprivate(set) var overlay: AlertOverlay
fileprivate(set) var backgroundColor: Color
fileprivate(set) var titleFont: Font
fileprivate(set) var titleColor: Color
fileprivate(set) var messageFont: Font
fileprivate(set) var messageColor: Color
fileprivate(set) var buttonTitleFont: Font
fileprivate(set) var buttonTitleColor: Color
fileprivate(set) var buttonBackgroundColor: Color
fileprivate(set) var cancelButtonBackgroundColor: Color
fileprivate(set) var cancelButtonTitleColor: Color
fileprivate(set) var destructBackgroundColor: Color
fileprivate(set) var destructTitleColor: Color
fileprivate(set) var shape: AlertShape
// MARK: Public
public class var theme: AlertTheme {
get {
return AlertTheme(overlay: .blurEffect(UIBlurEffectStyle.dark),
backgroundColor: Color.backgroundColor,
titleFont: Font.boldSystemFont(ofSize: 18),
titleColor: Color.textColor,
messageFont: Font.systemFont(ofSize: 16),
messageColor: Color.textColor,
buttonTitleFont: Font.boldSystemFont(ofSize: 16),
buttonTitleColor: Color.black.withAlphaComponent(0.85),
buttonBackgroundColor: Color.otherColor,
cancelButtonBackgroundColor: Color.cancelColor,
cancelButtonTitleColor: Color.black,
destructBackgroundColor: Color.destructiveColor,
destructTitleColor: Color.white,
shape: AlertShape.rounded(2.0))
}
}
// MARK: Initialization
internal init(overlay: AlertOverlay,
backgroundColor: UIColor,
titleFont: Font,
titleColor: Color,
messageFont: Font,
messageColor: Color,
buttonTitleFont: Font,
buttonTitleColor: Color,
buttonBackgroundColor: Color,
cancelButtonBackgroundColor: Color,
cancelButtonTitleColor: Color,
destructBackgroundColor: Color,
destructTitleColor: Color,
shape: AlertShape) {
self.overlay = overlay
self.backgroundColor = backgroundColor
self.titleFont = titleFont
self.titleColor = titleColor
self.messageFont = messageFont
self.messageColor = messageColor
self.buttonTitleFont = buttonTitleFont
self.buttonTitleColor = buttonTitleColor
self.buttonBackgroundColor = buttonBackgroundColor
self.cancelButtonBackgroundColor = cancelButtonBackgroundColor
self.cancelButtonTitleColor = cancelButtonTitleColor
self.destructBackgroundColor = destructBackgroundColor
self.destructTitleColor = destructTitleColor
self.shape = shape
}
public func overlay(_ overlay: AlertOverlay) -> AlertTheme {
self.overlay = overlay
return self
}
public func backgroundColor(_ background: UIColor) -> AlertTheme {
self.backgroundColor = background
return self
}
public func titleFont(_ font: Font) -> AlertTheme {
self.titleFont = font
return self
}
public func titleColor(_ color: Color) -> AlertTheme {
self.titleColor = color
return self
}
public func messageFont(_ font: Font) -> AlertTheme {
self.messageFont = font
return self
}
public func messageColor(_ color: Color) -> AlertTheme {
self.messageColor = color
return self
}
public func buttonTitleFont(_ font: Font) -> AlertTheme {
self.buttonTitleFont = font
return self
}
public func buttonTitleColor(_ color: Color) -> AlertTheme {
self.buttonTitleColor = color
return self
}
public func buttonBackgroundColor(_ color: Color) -> AlertTheme {
self.buttonBackgroundColor = color
return self
}
public func cancelBackgroundColor(_ color: Color) -> AlertTheme {
self.cancelButtonBackgroundColor = color
return self
}
public func cancelTitleColor(_ color: Color) -> AlertTheme {
self.cancelButtonTitleColor = color
return self
}
public func destructBackgroundColor(_ color: Color) -> AlertTheme {
self.destructBackgroundColor = color
return self
}
public func destructTitleColor(_ color: Color) -> AlertTheme {
self.destructTitleColor = color
return self
}
public func shape(_ shape: AlertShape) -> AlertTheme {
self.shape = shape
return self
}
internal func isBlurEffectView() -> Any {
if case AlertOverlay.blurEffect(let style) = self.overlay {
return style
} else {
return false
}
}
}
extension UIColor {
convenience init(r: CGFloat, g: CGFloat, b: CGFloat, a: CGFloat = 1) {
self.init(red: r / 255.0, green: g / 255.0, blue: b / 255.0, alpha: a)
}
convenience init(hex: Int) {
self.init(red: CGFloat((hex & 0xFF0000) >> 16) / 255.0, green: CGFloat((hex & 0xFF00) >> 8) / 255.0, blue: CGFloat(hex & 0xFF) / 255.0, alpha: 1.0)
}
class var backgroundColor: UIColor {
get {
return UIColor(r: 239, g: 240, b: 242)
}
}
class var overlayColor: UIColor {
get {
return UIColor(r: 0, g: 0, b: 0, a: 0.5)
}
}
class var textColor: UIColor {
get {
return UIColor(r: 77, g: 77, b: 77)
}
}
class var destructiveColor: UIColor {
get {
return UIColor(r: 231, g: 76, b: 70)
}
}
class var cancelColor: UIColor {
get {
return UIColor(r: 245, g: 245, b: 245, a: 1)
}
}
class var otherColor: UIColor {
get {
return UIColor(r: 245, g: 245, b: 245)
}
}
}
| mit | 7dd21b9a13835d9fdd8a2e2d57573c91 | 30.596154 | 155 | 0.602678 | 5.046069 | false | false | false | false |
vinsan/presteasymo | presteasymo/presteasymo/AppDelegate.swift | 1 | 8197 | //
// AppDelegate.swift
// presteasymo
//
// Created by Vincenzo Santoro on 03/04/2017.
// Copyright © 2017 Team 2.4. All rights reserved.
//
import UIKit
import CoreData
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
let gestCanc = GestoreCoreDataCancellazione()
let gestPrel = GestoreCoreDataPrelievo()
let gest1 = CoreDataController()
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
if let tabBarController = self.window!.rootViewController as? UITabBarController {
tabBarController.selectedIndex = 1
}
print("inseriamo una band ed un utente")
//creaUser(name: String, surname: String, city: String, email: String, password:String)
gest1.creaUser(name: "Marco", surname: "Rossi", city: "Avellino", email: "", password: "asd")
gest1.creaUser(name: "Luca", surname: "Verdi", city: "Roma", email: "asd", password: "asd")
gest1.creaUser(name: "Roberto", surname: "Neri", city: "Salerno", email: "asd", password: "asd")
gest1.creaUser(name: "Matteo", surname: "Treo", city: "Sava", email: "asd", password: "asd")
gest1.creaBand(name: "Pink floyd", areaCity: "roma", contactNumber: "789", youtubeChannel: "dfd", bandPhoto: "rerer", id: "pink")
print("fatto ora li preleviamo")
let ba=gestPrel.getBand()
let ut=gestPrel.getUser()
print("ora inseriamo un genere, feedback, abilità e membro ad utente ad una band")
let user = ut[1]
let band = ba[1]
if(!(user==nil)){
print("fatto 1")
let ab=gest1.creaAbility(name: "Guitar")
print("fatto 2")
let role=gest1.creaRole(id: "Erer", name: "pianista")
print("fatto 3")
let fee=gest1.creaFeedBack(voto: 45, utente: user, ability: ab)
print("fatto4")
let genre=gest1.creaMusicalGeneral(name: "Rock", id: "erer", utente: user, band: band)
print("fatto 5")
let membro=gest1.creaBandMember(leader: false, user: user, band: band, ruolo: role)
user.addAbility(value: ab)
user.addGenere(value: genre)
user.addMembro(value: membro)
user.addValutazione(value: fee)
}
if(!(band==nil)){
print("fatto 34")
let ruolo3=gest1.creaRole(id: "trt", name: "Guitar")
print("fatto 35")
let membro1=gest1.creaBandMember(leader: true, user: user, band: band, ruolo: ruolo3)
print("fatto 36")
let genre3=gest1.creaMusicalGeneral(name: "jazz", id: "tyty", utente: user, band: band)
print("fatto 37")
band.addGenereBand(value: genre3)
band.addMembroBand(value: membro1)
}
print("ora visualizziamo i contenuti inseriti nell'utente e nella band")
let feeds=gestPrel.getFeedBackUser(user: user)
let abs=gestPrel.getAbilityUser(user: user)
let userMe=gestPrel.getBandMembroUser(user: user)
let gens=gestPrel.getGenereUser(user: user)
let genBand=gestPrel.getGenereBand(user: band)
let membro=gestPrel.getMembroBand(user: band)
for f1 in feeds{
print("FeedBack " ,f1.evalutation , f1.user!.name! + f1.ability!.name!)
}
for f2 in abs{
print("ability " + f2.name! + f2.user!.name!)
}
for f3 in userMe{
print("UserMember " + f3.user!.name! + f3.role!.name!)
}
for f4 in gens{
print("Genere " + f4.name! + f4.userGenre!.name! + f4.bandGenre!.name!)
}
for f5 in genBand{
print("GenereBand " ,f5.name! + f5.bandGenre!.name!)
}
for f6 in membro{
print("MembroBand" + f6.user!.name! + f6.role!.name!)
}
return true
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
// Saves changes in the application's managed object context before the application terminates.
self.saveContext()
}
// MARK: - Core Data stack
lazy var persistentContainer: NSPersistentContainer = {
/*
The persistent container for the application. This implementation
creates and returns a container, having loaded 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.
*/
let container = NSPersistentContainer(name: "presteasymo")
container.loadPersistentStores(completionHandler: { (storeDescription, error) in
if let error = error as NSError? {
// Replace this implementation with code to handle the error appropriately.
// fatalError() 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.
/*
Typical reasons for an error here include:
* The parent directory does not exist, cannot be created, or disallows writing.
* The persistent store is not accessible, due to permissions or data protection when the device is locked.
* The device is out of space.
* The store could not be migrated to the current model version.
Check the error message to determine what the actual problem was.
*/
fatalError("Unresolved error \(error), \(error.userInfo)")
}
})
return container
}()
// MARK: - Core Data Saving support
func saveContext () {
let context = persistentContainer.viewContext
if context.hasChanges {
do {
try context.save()
} catch {
// Replace this implementation with code to handle the error appropriately.
// fatalError() 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.
let nserror = error as NSError
fatalError("Unresolved error \(nserror), \(nserror.userInfo)")
}
}
}
}
| apache-2.0 | c0596cf9408378d5ea5237a82b0ce29b | 44.527778 | 285 | 0.63014 | 4.377671 | false | false | false | false |
payjp/payjp-ios | Sources/Validators/CardNumberValidator.swift | 1 | 2088 | //
// CardNumberValidator.swift
// PAYJP
//
// Created by Tadashi Wakayanagi on 2019/07/19.
// Copyright © 2019 PAY, Inc. All rights reserved.
//
import Foundation
protocol CardNumberValidatorType {
/// カード番号のバリデーションチェックを行う
///
/// - Parameters:
/// - cardNumber: cardNumber カード番号
/// - brand: brand カードブランド
/// - Returns: true バリデーションOK
func isValid(cardNumber: String, brand: CardBrand) -> Bool
/// カード番号の長さをチェックする
///
/// - Parameters:
/// - cardNumber: cardNumber カード番号
/// - brand: brand カードブランド
/// - Returns: true 長さが正しい
func isCardNumberLengthValid(cardNumber: String, brand: CardBrand) -> Bool
/// カード番号のチェックディジットを行う
///
/// - Parameter cardNumber: カード番号
/// - Returns: true チェックディジットOK
func isLuhnValid(cardNumber: String) -> Bool
}
struct CardNumberValidator: CardNumberValidatorType {
func isValid(cardNumber: String, brand: CardBrand) -> Bool {
let filtered = cardNumber.numberfy()
if cardNumber.count != filtered.count {
return false
}
return isCardNumberLengthValid(cardNumber: filtered, brand: brand) && isLuhnValid(cardNumber: filtered)
}
func isCardNumberLengthValid(cardNumber: String, brand: CardBrand) -> Bool {
return cardNumber.count == brand.numberLength
}
func isLuhnValid(cardNumber: String) -> Bool {
var sum = 0
let digitStrings = cardNumber.reversed().map(String.init).map(Int.init)
for (offset, element) in digitStrings.enumerated() {
if var digit = element {
let odd = offset % 2 == 1
if odd {
digit *= 2
}
if digit > 9 {
digit -= 9
}
sum += digit
}
}
return sum % 10 == 0
}
}
| mit | deb7774782326b6ddc8ee67041eccd6b | 27.907692 | 111 | 0.580628 | 3.955789 | false | false | false | false |
takev/DimensionsCAM | DimensionsCAM/OpenSCADCSG_tests.swift | 1 | 10865 | // DimensionsCAM - A multi-axis tool path generator for a milling machine
// Copyright (C) 2015 Take Vos
//
// 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.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
import XCTest
import simd
func XCTAssertEqualThrows<T: Equatable>(
@autoclosure expression1: () throws -> T?,
@autoclosure _ expression2: () throws -> T?,
_ message: String = "",
file: String = __FILE__,
line: UInt = __LINE__
) {
var result1: T? = nil
var result2: T? = nil
var error1: ErrorType? = nil
var error2: ErrorType? = nil
do {
result1 = try expression1()
} catch {
error1 = error
}
do {
result2 = try expression2()
} catch {
error2 = error
}
if result1 != nil && result2 != nil {
XCTAssertEqual(result1!, result2!, message, file:file, line:line)
} else if error1 != nil {
XCTFail("left expression throws \(error1)", file:file, line:line)
} else if error2 != nil {
XCTFail("right expression throws \(error2)", file:file, line:line)
}
}
class OpenSCADCSG_tests: XCTestCase {
let test1 = String(sep:"\n",
"foo() {",
" bar([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]], top=[1, 2.0e-3, -3.5, 4], center = 5, $f=6);",
"}\n"
)
let test2 = String(sep:"\n",
"group() {",
" multmatrix([[1, 0, 0, 40], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1]]) {",
" difference() {",
" union() {",
" cube(size = [100, 100, 100], center = true);",
" multmatrix([[1, 0, 0, 49.9], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1]]) {",
" multmatrix([[2.22045e-16, 0, 1, 0], [0, 1, 0, 0], [-1, 0, 2.22045e-16, 0], [0, 0, 0, 1]]) {",
" cylinder($fn = 0, $fa = 2, $fs = 2, h = 200, r1 = 50, r2 = 50, center = false);",
" }",
" }",
" }",
" union() {",
" multmatrix([[1, 0, 0, 150], [0, 1, 0, -44], [0, 0, 1, 10], [0, 0, 0, 1]]) {",
" multmatrix([[1, 0, 0, 0], [0, 0.939693, -0.34202, 0], [0, 0.34202, 0.939693, 0], [0, 0, 0, 1]]) {",
" cube(size = [40, 40, 110], center = true);",
" }",
" }",
" multmatrix([[1, 0, 0, 150], [0, 1, 0, 30], [0, 0, 1, -25], [0, 0, 0, 1]]) {",
" multmatrix([[1, 0, 0, 0], [0, -0.173648, -0.984808, 0], [0, 0.984808, -0.173648, 0], [0, 0, 0, 1]]) {",
" cylinder($fn = 0, $fa = 2, $fs = 2, h = 50, r1 = 10, r2 = 10, center = false);",
" }",
" }",
" }",
" }",
" }",
"}\n"
)
override func setUp() {
super.setUp()
}
override func tearDown() {
super.tearDown()
}
func testLexer() {
var p = OpenSCADCSGLexer(text:test1, filename:"<test1>")
XCTAssertEqualThrows(try p.getToken(), OpenSCADCSGToken.NAME("foo"))
XCTAssertEqualThrows(try p.getToken(), OpenSCADCSGToken.LEFT_PARENTHESIS)
XCTAssertEqualThrows(try p.getToken(), OpenSCADCSGToken.RIGHT_PARENTHESIS)
XCTAssertEqualThrows(try p.getToken(), OpenSCADCSGToken.LEFT_BRACE)
XCTAssertEqualThrows(try p.getToken(), OpenSCADCSGToken.NAME("bar"))
XCTAssertEqualThrows(try p.getToken(), OpenSCADCSGToken.LEFT_PARENTHESIS)
XCTAssertEqualThrows(try p.getToken(), OpenSCADCSGToken.LEFT_BRACKET)
XCTAssertEqualThrows(try p.getToken(), OpenSCADCSGToken.LEFT_BRACKET)
XCTAssertEqualThrows(try p.getToken(), OpenSCADCSGToken.NUMBER(1.0))
XCTAssertEqualThrows(try p.getToken(), OpenSCADCSGToken.COMMA)
XCTAssertEqualThrows(try p.getToken(), OpenSCADCSGToken.NUMBER(2.0))
XCTAssertEqualThrows(try p.getToken(), OpenSCADCSGToken.COMMA)
XCTAssertEqualThrows(try p.getToken(), OpenSCADCSGToken.NUMBER(3.0))
XCTAssertEqualThrows(try p.getToken(), OpenSCADCSGToken.COMMA)
XCTAssertEqualThrows(try p.getToken(), OpenSCADCSGToken.NUMBER(4.0))
XCTAssertEqualThrows(try p.getToken(), OpenSCADCSGToken.RIGHT_BRACKET)
XCTAssertEqualThrows(try p.getToken(), OpenSCADCSGToken.COMMA)
XCTAssertEqualThrows(try p.getToken(), OpenSCADCSGToken.LEFT_BRACKET)
XCTAssertEqualThrows(try p.getToken(), OpenSCADCSGToken.NUMBER(5.0))
XCTAssertEqualThrows(try p.getToken(), OpenSCADCSGToken.COMMA)
XCTAssertEqualThrows(try p.getToken(), OpenSCADCSGToken.NUMBER(6.0))
XCTAssertEqualThrows(try p.getToken(), OpenSCADCSGToken.COMMA)
XCTAssertEqualThrows(try p.getToken(), OpenSCADCSGToken.NUMBER(7.0))
XCTAssertEqualThrows(try p.getToken(), OpenSCADCSGToken.COMMA)
XCTAssertEqualThrows(try p.getToken(), OpenSCADCSGToken.NUMBER(8.0))
XCTAssertEqualThrows(try p.getToken(), OpenSCADCSGToken.RIGHT_BRACKET)
XCTAssertEqualThrows(try p.getToken(), OpenSCADCSGToken.COMMA)
XCTAssertEqualThrows(try p.getToken(), OpenSCADCSGToken.LEFT_BRACKET)
XCTAssertEqualThrows(try p.getToken(), OpenSCADCSGToken.NUMBER(9.0))
XCTAssertEqualThrows(try p.getToken(), OpenSCADCSGToken.COMMA)
XCTAssertEqualThrows(try p.getToken(), OpenSCADCSGToken.NUMBER(10.0))
XCTAssertEqualThrows(try p.getToken(), OpenSCADCSGToken.COMMA)
XCTAssertEqualThrows(try p.getToken(), OpenSCADCSGToken.NUMBER(11.0))
XCTAssertEqualThrows(try p.getToken(), OpenSCADCSGToken.COMMA)
XCTAssertEqualThrows(try p.getToken(), OpenSCADCSGToken.NUMBER(12.0))
XCTAssertEqualThrows(try p.getToken(), OpenSCADCSGToken.RIGHT_BRACKET)
XCTAssertEqualThrows(try p.getToken(), OpenSCADCSGToken.COMMA)
XCTAssertEqualThrows(try p.getToken(), OpenSCADCSGToken.LEFT_BRACKET)
XCTAssertEqualThrows(try p.getToken(), OpenSCADCSGToken.NUMBER(13.0))
XCTAssertEqualThrows(try p.getToken(), OpenSCADCSGToken.COMMA)
XCTAssertEqualThrows(try p.getToken(), OpenSCADCSGToken.NUMBER(14.0))
XCTAssertEqualThrows(try p.getToken(), OpenSCADCSGToken.COMMA)
XCTAssertEqualThrows(try p.getToken(), OpenSCADCSGToken.NUMBER(15.0))
XCTAssertEqualThrows(try p.getToken(), OpenSCADCSGToken.COMMA)
XCTAssertEqualThrows(try p.getToken(), OpenSCADCSGToken.NUMBER(16.0))
XCTAssertEqualThrows(try p.getToken(), OpenSCADCSGToken.RIGHT_BRACKET)
XCTAssertEqualThrows(try p.getToken(), OpenSCADCSGToken.RIGHT_BRACKET)
XCTAssertEqualThrows(try p.getToken(), OpenSCADCSGToken.COMMA)
XCTAssertEqualThrows(try p.getToken(), OpenSCADCSGToken.NAME("top"))
XCTAssertEqualThrows(try p.getToken(), OpenSCADCSGToken.EQUAL)
XCTAssertEqualThrows(try p.getToken(), OpenSCADCSGToken.LEFT_BRACKET)
XCTAssertEqualThrows(try p.getToken(), OpenSCADCSGToken.NUMBER(1.0))
XCTAssertEqualThrows(try p.getToken(), OpenSCADCSGToken.COMMA)
XCTAssertEqualThrows(try p.getToken(), OpenSCADCSGToken.NUMBER(2.0e-3))
XCTAssertEqualThrows(try p.getToken(), OpenSCADCSGToken.COMMA)
XCTAssertEqualThrows(try p.getToken(), OpenSCADCSGToken.NUMBER(-3.5))
XCTAssertEqualThrows(try p.getToken(), OpenSCADCSGToken.COMMA)
XCTAssertEqualThrows(try p.getToken(), OpenSCADCSGToken.NUMBER(4))
XCTAssertEqualThrows(try p.getToken(), OpenSCADCSGToken.RIGHT_BRACKET)
XCTAssertEqualThrows(try p.getToken(), OpenSCADCSGToken.COMMA)
XCTAssertEqualThrows(try p.getToken(), OpenSCADCSGToken.NAME("center"))
XCTAssertEqualThrows(try p.getToken(), OpenSCADCSGToken.EQUAL)
XCTAssertEqualThrows(try p.getToken(), OpenSCADCSGToken.NUMBER(5))
XCTAssertEqualThrows(try p.getToken(), OpenSCADCSGToken.COMMA)
XCTAssertEqualThrows(try p.getToken(), OpenSCADCSGToken.NAME("$f"))
XCTAssertEqualThrows(try p.getToken(), OpenSCADCSGToken.EQUAL)
XCTAssertEqualThrows(try p.getToken(), OpenSCADCSGToken.NUMBER(6))
XCTAssertEqualThrows(try p.getToken(), OpenSCADCSGToken.RIGHT_PARENTHESIS)
XCTAssertEqualThrows(try p.getToken(), OpenSCADCSGToken.SEMICOLON)
XCTAssertEqualThrows(try p.getToken(), OpenSCADCSGToken.RIGHT_BRACE)
XCTAssertEqualThrows(try p.getToken(), OpenSCADCSGToken.END_OF_FILE)
}
func testGrammar() {
var p = OpenSCADCSGGrammar(text: test1, filename: "<test1>")
let expected: OpenSCADCSGAST = .BRANCH("program", [
.BRANCH("function", [
.LEAF_NAME("foo"),
.BRANCH("arguments", []),
.BRANCH("block", [
.BRANCH("function", [
.LEAF_NAME("bar"),
.BRANCH("arguments", [
.BRANCH("argument", [
.NULL,
.LEAF_MATRIX(double4x4(rows:[double4(1, 2, 3, 4), double4(5, 6, 7, 8), double4(9, 10, 11, 12), double4(13, 14, 15, 16)]))
]),
.BRANCH("argument", [
.LEAF_NAME("top"),
.LEAF_VECTOR(double4(1.0, 0.002, -3.5, 4))
]),
.BRANCH("argument", [
.LEAF_NAME("center"),
.LEAF_NUMBER(5)
]),
.BRANCH("argument", [
.LEAF_NAME("$f"),
.LEAF_NUMBER(6)
])
]),
.BRANCH("block", [])
])
])
])
])
XCTAssertEqualThrows(try p.parseProgram(), expected)
}
func testParser() {
Interval.setRoundMode()
var p = OpenSCADCSGParser(text: test2, filename: "<test2>")
let csg_tree = try! p.parseProgram()
Swift.print(csg_tree)
csg_tree.update(double4x4.identity)
Swift.print(csg_tree.boundingBox)
}
}
| gpl-3.0 | 18d6d3ad5bb37d50e09b396c3e44764f | 47.721973 | 153 | 0.582789 | 4.137471 | false | true | false | false |
maicki/plank | Examples/Cocoa/Tests/Objective_CTests/ObjcJSBridgingTests.swift | 1 | 2691 | import Foundation
import JavaScriptCore
import XCTest
@testable import Objective_C
class ObjcJavaScriptCoreBridgingTestSuite: XCTestCase {
static let _context: JSContext = JSContext()!
override class func setUp() {
super.setUp();
injectJSFileIntoContext(fileName: "bundle", context: _context);
}
// Inject a js file located in plank/Examples/Shared/
class func injectJSFileIntoContext(fileName: String, context: JSContext) {
let jsFileName = "\(fileName).js"
// The currentDirectoryPath is: plank/Examples/Cocoa/
let currentPath = FileManager.default.currentDirectoryPath
let pathURL = URL(fileURLWithPath: currentPath)
let finalPathURL = pathURL.appendingPathComponent("..")
.appendingPathComponent("Shared")
.appendingPathComponent(jsFileName)
do {
let bundleContents = try String(contentsOf: finalPathURL, encoding: .utf8)
context.evaluateScript(bundleContents)
} catch {
print("Couldn't inject \(jsFileName) into JSContext")
}
}
var context: JSContext {
return ObjcJavaScriptCoreBridgingTestSuite._context
}
func testImageModelBridgingGetImage() {
// Expected modelc dictionary
let imageModelDictionary: JSONDict = [
"height": 300,
"width": 200,
"url": "https://picsum.photos/200/300"
]
let expectedImage = Image(modelDictionary: imageModelDictionary);
let expectedImageDictionaryRepresentation = expectedImage.dictionaryObjectRepresentation()
// Get image from js context
let getTestImageModelJSONFunction = context.objectForKeyedSubscript("getTestImageModelJSON")!
let jsImageModel = getTestImageModelJSONFunction.call(withArguments:[]).toObject() as! JSONDict
XCTAssert(expectedImage.isEqual(to: Image(modelDictionary:jsImageModel)))
XCTAssert(jsImageModel == expectedImageDictionaryRepresentation)
}
func testImageModelBridgingSendImage() {
// Expected model dictionary
let imageModelDictionary: JSONDict = [
"height": 300,
"width": 200,
"url": "https://picsum.photos/200/300"
]
let imageModel = Image(modelDictionary: imageModelDictionary);
let imageModelDictionaryRepresentation = imageModel.dictionaryObjectRepresentation()
let testImageModelJSON = context.objectForKeyedSubscript("sendTestImageModelJSON")!
XCTAssert(testImageModelJSON.call(withArguments:[imageModelDictionaryRepresentation]).toBool())
}
}
| apache-2.0 | 9693bb50a67f912298de97bfb0602f51 | 38 | 103 | 0.671498 | 5.414487 | false | true | false | false |
Johnykutty/SwiftLint | Source/SwiftLintFramework/Rules/StatementPositionRule.swift | 2 | 9447 | //
// StatementPositionRule.swift
// SwiftLint
//
// Created by Alex Culeva on 10/22/15.
// Copyright © 2015 Realm. All rights reserved.
//
import Foundation
import SourceKittenFramework
public struct StatementPositionRule: CorrectableRule, ConfigurationProviderRule {
public var configuration = StatementConfiguration(statementMode: .default,
severity: SeverityConfiguration(.warning))
public init() {}
public static let description = RuleDescription(
identifier: "statement_position",
name: "Statement Position",
description: "Else and catch should be on the same line, one space after the previous " +
"declaration.",
nonTriggeringExamples: [
"} else if {",
"} else {",
"} catch {",
"\"}else{\"",
"struct A { let catchphrase: Int }\nlet a = A(\n catchphrase: 0\n)",
"struct A { let `catch`: Int }\nlet a = A(\n `catch`: 0\n)"
],
triggeringExamples: [
"↓}else if {",
"↓} else {",
"↓}\ncatch {",
"↓}\n\t catch {"
],
corrections: [
"↓}\n else {\n": "} else {\n",
"↓}\n else if {\n": "} else if {\n",
"↓}\n catch {\n": "} catch {\n"
]
)
public static let uncuddledDescription = RuleDescription(
identifier: "statement_position",
name: "Statement Position",
description: "Else and catch should be on the next line, with equal indentation to the " +
"previous declaration.",
nonTriggeringExamples: [
" }\n else if {",
" }\n else {",
" }\n catch {",
" }\n\n catch {",
"\n\n }\n catch {",
"\"}\nelse{\"",
"struct A { let catchphrase: Int }\nlet a = A(\n catchphrase: 0\n)",
"struct A { let `catch`: Int }\nlet a = A(\n `catch`: 0\n)"
],
triggeringExamples: [
"↓ }else if {",
"↓}\n else {",
"↓ }\ncatch {",
"↓}\n\t catch {"
],
corrections: [
" }else if {": " }\n else if {",
"}\n else {": "}\nelse {",
" }\ncatch {": " }\n catch {",
"}\n\t catch {": "}\ncatch {"
]
)
public func validate(file: File) -> [StyleViolation] {
switch configuration.statementMode {
case .default:
return defaultValidate(file: file)
case .uncuddledElse:
return uncuddledValidate(file: file)
}
}
public func correct(file: File) -> [Correction] {
switch configuration.statementMode {
case .default:
return defaultCorrect(file: file)
case .uncuddledElse:
return uncuddledCorrect(file: file)
}
}
}
// Default Behaviors
private extension StatementPositionRule {
// match literal '}'
// followed by 1) nothing, 2) two+ whitespace/newlines or 3) newlines or tabs
// followed by 'else' or 'catch' literals
static let defaultPattern = "\\}(?:[\\s\\n\\r]{2,}|[\\n\\t\\r]+)?\\b(else|catch)\\b"
func defaultValidate(file: File) -> [StyleViolation] {
return defaultViolationRanges(in: file, matching: type(of: self).defaultPattern).flatMap { range in
return StyleViolation(ruleDescription: type(of: self).description,
severity: configuration.severity.severity,
location: Location(file: file, characterOffset: range.location))
}
}
func defaultViolationRanges(in file: File, matching pattern: String) -> [NSRange] {
return file.match(pattern: pattern).filter { _, syntaxKinds in
return syntaxKinds.starts(with: [.keyword])
}.flatMap { $0.0 }
}
func defaultCorrect(file: File) -> [Correction] {
let violations = defaultViolationRanges(in: file, matching: type(of: self).defaultPattern)
let matches = file.ruleEnabled(violatingRanges: violations, for: self)
if matches.isEmpty { return [] }
let regularExpression = regex(type(of: self).defaultPattern)
let description = type(of: self).description
var corrections = [Correction]()
var contents = file.contents
for range in matches.reversed() {
contents = regularExpression.stringByReplacingMatches(in: contents, options: [], range: range,
withTemplate: "} $1")
let location = Location(file: file, characterOffset: range.location)
corrections.append(Correction(ruleDescription: description, location: location))
}
file.write(contents)
return corrections
}
}
// Uncuddled Behaviors
private extension StatementPositionRule {
func uncuddledValidate(file: File) -> [StyleViolation] {
return uncuddledViolationRanges(in: file).flatMap { range in
return StyleViolation(ruleDescription: type(of: self).uncuddledDescription,
severity: configuration.severity.severity,
location: Location(file: file, characterOffset: range.location))
}
}
// match literal '}'
// preceded by whitespace (or nothing)
// followed by 1) nothing, 2) two+ whitespace/newlines or 3) newlines or tabs
// followed by newline and the same amount of whitespace then 'else' or 'catch' literals
static let uncuddledPattern = "([ \t]*)\\}(\\n+)?([ \t]*)\\b(else|catch)\\b"
static let uncuddledRegex = regex(uncuddledPattern, options: [])
static func uncuddledMatchValidator(contents: String) -> ((NSTextCheckingResult) -> NSTextCheckingResult?) {
return { match in
if match.numberOfRanges != 5 {
return match
}
if match.rangeAt(2).length == 0 {
return match
}
let range1 = match.rangeAt(1)
let range2 = match.rangeAt(3)
let whitespace1 = contents.substring(from: range1.location, length: range1.length)
let whitespace2 = contents.substring(from: range2.location, length: range2.length)
if whitespace1 == whitespace2 {
return nil
}
return match
}
}
static func uncuddledMatchFilter(contents: String, syntaxMap: SyntaxMap) -> ((NSTextCheckingResult) -> Bool) {
return { match in
let range = match.range
guard let matchRange = contents.bridge().NSRangeToByteRange(start: range.location,
length: range.length) else {
return false
}
let tokens = syntaxMap.tokens(inByteRange: matchRange).flatMap { SyntaxKind(rawValue: $0.type) }
return tokens == [.keyword]
}
}
func uncuddledViolationRanges(in file: File) -> [NSRange] {
let contents = file.contents
let range = NSRange(location: 0, length: contents.utf16.count)
let syntaxMap = file.syntaxMap
let matches = StatementPositionRule.uncuddledRegex.matches(in: contents, options: [], range: range)
let validator = type(of: self).uncuddledMatchValidator(contents: contents)
let filterMatches = type(of: self).uncuddledMatchFilter(contents: contents, syntaxMap: syntaxMap)
let validMatches = matches.flatMap(validator).filter(filterMatches).map({ $0.range })
return validMatches
}
func uncuddledCorrect(file: File) -> [Correction] {
var contents = file.contents
let range = NSRange(location: 0, length: contents.utf16.count)
let syntaxMap = file.syntaxMap
let matches = StatementPositionRule.uncuddledRegex.matches(in: contents, options: [], range: range)
let validator = type(of: self).uncuddledMatchValidator(contents: contents)
let filterRanges = type(of: self).uncuddledMatchFilter(contents: contents, syntaxMap: syntaxMap)
let validMatches = matches.flatMap(validator).filter(filterRanges)
.filter { !file.ruleEnabled(violatingRanges: [$0.range], for: self).isEmpty }
if validMatches.isEmpty { return [] }
let description = type(of: self).uncuddledDescription
var corrections = [Correction]()
for match in validMatches.reversed() {
let range1 = match.rangeAt(1)
let range2 = match.rangeAt(3)
let newlineRange = match.rangeAt(2)
var whitespace = contents.bridge().substring(with: range1)
let newLines: String
if newlineRange.location != NSNotFound {
newLines = contents.bridge().substring(with: newlineRange)
} else {
newLines = ""
}
if !whitespace.hasPrefix("\n") && newLines != "\n" {
whitespace.insert("\n", at: whitespace.startIndex)
}
contents = contents.bridge().replacingCharacters(in: range2, with: whitespace)
let location = Location(file: file, characterOffset: match.range.location)
corrections.append(Correction(ruleDescription: description, location: location))
}
file.write(contents)
return corrections
}
}
| mit | 04420026c3e229c360f07c18fd944763 | 39.62069 | 114 | 0.578417 | 4.55706 | false | false | false | false |
wwq0327/iOS8Example | Diary/Diary/DiaryYearCollectionViewController.swift | 1 | 5849 | //
// DiaryYearCollectionViewController.swift
// Diary
//
// Created by wyatt on 15/6/14.
// Copyright (c) 2015年 Wanqing Wang. All rights reserved.
//
import UIKit
import CoreData
class DiaryYearCollectionViewController: UICollectionViewController {
var year: Int!
var yearLabel: UILabel!
var composeButton: UIButton!
// data
var diarys = [NSManagedObject]()
var fetchedResultsController: NSFetchedResultsController!
override func viewDidLoad() {
super.viewDidLoad()
loadData()
yearLabel = DiaryLabel(fontname: "TpldKhangXiDictTrial", labelText: "\(numberToChinese(year))年", fontSize: 20.0, lineHeight: 5.0)
yearLabel.center = CGPointMake(screenRect.width-yearLabel.frame.size.width/2.0-15, 20+yearLabel.frame.size.height/2.0)
self.view.addSubview(yearLabel)
yearLabel.userInteractionEnabled = true
var mTapUpRecognizer = UITapGestureRecognizer(target: self, action: "backToHome")
mTapUpRecognizer.numberOfTapsRequired = 1
yearLabel.addGestureRecognizer(mTapUpRecognizer)
var composeButton = diaryButtonWith(text: "撰", fontSize: 14.0, width: 40.0, normalImageName: "Oval", highlightedImageName: "Oval_pressed")
composeButton.center = CGPointMake(yearLabel.center.x, 38 + yearLabel.frame.size.height + 26.0/2.0)
composeButton.addTarget(self, action: "newCompose", forControlEvents: UIControlEvents.TouchUpInside)
self.view.addSubview(composeButton)
var yearLayout = DiaryLayout()
yearLayout.scrollDirection = UICollectionViewScrollDirection.Horizontal
self.collectionView?.setCollectionViewLayout(yearLayout, animated: false)
self.collectionView?.frame = CGRect(x: 0, y: 0, width: collectionViewWidth, height: itemHeight)
self.collectionView?.center = CGPoint(x: self.view.frame.size.width/2.0, y: self.view.frame.size.height/2.0)
self.view.backgroundColor = UIColor.whiteColor()
}
func loadData() {
let fetchRequest = NSFetchRequest(entityName: "Diary")
var error: NSError?
var year = 2015
var month = 6
let fetchedResults = managedContext.executeFetchRequest(fetchRequest, error: &error) as! [NSManagedObject]?
fetchRequest.sortDescriptors = [NSSortDescriptor(key: "created_at", ascending: true)] // 排序方式
fetchRequest.predicate = NSPredicate(format: "year = \(year) AND month = \(month)")
fetchedResultsController = NSFetchedResultsController(fetchRequest: fetchRequest, managedObjectContext: managedContext, sectionNameKeyPath: "month", cacheName: nil)
if !fetchedResultsController.performFetch(&error) {
println("Present empty year")
} else {
diarys = fetchedResults!
}
}
func newCompose() {
let composeViewController = self.storyboard?.instantiateViewControllerWithIdentifier(StoryboardIdentifiers.diaryComposeViewController) as! DiaryComposeViewController
self.presentViewController(composeViewController, animated: true, completion: nil)
}
// MARK: UICollectionViewDataSource
override func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
//#warning Incomplete method implementation -- Return the number of sections
return 1
}
override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
//#warning Incomplete method implementation -- Return the number of items in the section
return 1
}
override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier(CollectionCellIdetifiers.diaryCellIdentifiers, forIndexPath: indexPath) as! DiaryCollectionViewCell
if fetchedResultsController.sections?.count == 0 {
cell.labelText = "\(numberToChineseWithUnit(NSCalendar.currentCalendar().component(NSCalendarUnit.CalendarUnitMonth, fromDate: NSDate()))) 月"
} else {
let sectionInfo = fetchedResultsController.sections![indexPath.row] as! NSFetchedResultsSectionInfo
var month = sectionInfo.name?.toInt()
cell.labelText = "\(numberToChineseWithUnit(month!)) 月"
}
return cell
}
// 加载场景
override func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier(CollectionCellIdetifiers.diaryCellIdentifiers, forIndexPath: indexPath) as! DiaryCollectionViewCell
var dvc = self.storyboard?.instantiateViewControllerWithIdentifier(StoryboardIdentifiers.diaryMonthIdentifiers) as! DiaryMonthDayCollectionViewController
if fetchedResultsController.sections?.count == 0 {
dvc.month = NSCalendar.currentCalendar().component(NSCalendarUnit.CalendarUnitMonth, fromDate: NSDate())
}else{
let sectionInfo = fetchedResultsController.sections![indexPath.row] as! NSFetchedResultsSectionInfo
var month = sectionInfo.name?.toInt()
dvc.month = month!
}
dvc.year = year
self.navigationController?.pushViewController(dvc, animated: true)
}
// 文字居中
func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAtIndex section: Int) -> UIEdgeInsets {
var leftRightMagrin = (collectionViewWidth - itemWidth)/2
return UIEdgeInsetsMake(0, leftRightMagrin, 0, leftRightMagrin);
}
}
| apache-2.0 | 3915339f4a0eae593f2d78a091390e03 | 44.429688 | 173 | 0.707825 | 5.384259 | false | false | false | false |
OpenKitten/MongoKitten | Sources/MongoCore/Primitives/ConnectionSettings.swift | 2 | 12519 | import Foundation
fileprivate extension Bool {
init?(queryValue: String?) {
switch queryValue {
case nil:
return nil
case "0", "false", "FALSE":
self = false
default:
self = true
}
}
}
/// Describes the settings for a MongoDB connection, most of which can be represented in a connection string
public struct ConnectionSettings: Equatable {
/// The authentication details to use with the database
public enum Authentication: Equatable {
/// Unauthenticated
case unauthenticated
/// Automatically select the mechanism
case auto(username: String, password: String)
/// SCRAM-SHA1 mechanism
case scramSha1(username: String, password: String)
/// SCRAM-SHA256 mechanism
case scramSha256(username: String, password: String)
/// Deprecated MongoDB Challenge Response mechanism
case mongoDBCR(username: String, password: String)
}
/// Defines a MongoDB host
public struct Host: Hashable {
/// The hostname, like "localhost", "example.com" or "127.0.0.1"
public var hostname: String
/// The port. The default MongoDB port is 27017
public var port: Int
/// Initializes a new `Host` instance
///
/// - parameter hostname: The hostname
/// - parameter port: The port
public init(hostname: String, port: Int) {
self.hostname = hostname
self.port = port
}
public init<S: StringProtocol>(_ hostString: S, srv: Bool) throws {
let splitHost = hostString.split(separator: ":", maxSplits: 1)
let specifiesPort = splitHost.count == 2
if specifiesPort {
if srv {
throw MongoInvalidUriError(reason: .srvCannotSpecifyPort)
}
let specifiedPortString = splitHost[1]
guard let specifiedPort = Int(specifiedPortString) else {
throw MongoInvalidUriError(reason: .invalidPort)
}
port = specifiedPort
} else {
port = 27017
}
self.hostname = String(splitHost[0])
}
}
/// The authentication details (mechanism + credentials) to use
public var authentication: Authentication
/// Specify the database name associated with the user’s credentials. authSource defaults to the database specified in the connection string.
/// For authentication mechanisms that delegate credential storage to other services, the authSource value should be $external as with the PLAIN (LDAP) and GSSAPI (Kerberos) authentication mechanisms.
public var authenticationSource: String?
/// Hosts to connect to
public var hosts: [Host]
/// When true, SSL will be used
public var useSSL: Bool = false
/// When SSL is enabled, the CA certificate to use
/// If `nil`, don't use a custom CA
public var sslCaCertificatePath: String?
/// When true, SSL certificates will be validated
public var verifySSLCertificates: Bool = true
/// The maximum number of connections allowed
public var maximumNumberOfConnections: Int = 1
/// The connection timeout, in seconds. Defaults to 5 minutes.
public var connectTimeout: TimeInterval = 300
/// The time in seconds to attempt a send or receive on a socket before the attempt times out. Defaults to 5 minutes.
public var socketTimeout: TimeInterval = 300
/// The target path
public var targetDatabase: String?
/// The application name is printed to the mongod logs upon establishing the connection. It is also recorded in the slow query logs and profile collections.
public var applicationName: String?
/// Indicates that there is one host for which we'll need to do an query
public let isSRV: Bool
public var dnsServer: String?
public var queryParameters: [String: String]
/// Initializes a new connection settings instacen.
///
/// - parameter authentication: See `ConnectionSettings.Authentication`
/// - parameter authenticationSource: See `ConnectionSettings.authenticationSource`
/// - parameter hosts: Hosts to connect to
/// - parameter targetDatabase: The target path
/// - parameter useSSL: When true, SSL will be used
/// - parameter verifySSLCertificates: When true, SSL certificates will be validated
/// - parameter maximumNumberOfConnections: The maximum number of connections allowed
/// - parameter connectTimeout: See `ConnectionSettings.connectTimeout`
/// - parameter socketTimeout: See `ConnectionSettings.socketTimeout`
/// - parameter applicationName: The application name is printed to the mongod logs upon establishing the connection. It is also recorded in the slow query logs and profile collections.
public init(authentication: Authentication, authenticationSource: String? = nil, hosts: [Host], targetDatabase: String? = nil, useSSL: Bool = false, verifySSLCertificates: Bool = true, maximumNumberOfConnections: Int = 1, connectTimeout: TimeInterval = 300, socketTimeout: TimeInterval = 300, applicationName: String? = nil) {
self.authentication = authentication
self.authenticationSource = authenticationSource
self.hosts = hosts
self.targetDatabase = targetDatabase
self.useSSL = useSSL
self.verifySSLCertificates = verifySSLCertificates
self.maximumNumberOfConnections = maximumNumberOfConnections
self.connectTimeout = connectTimeout
self.socketTimeout = socketTimeout
self.applicationName = applicationName
self.isSRV = false
self.queryParameters = [:]
}
/// Parses the given `uri` into the ConnectionSettings
/// `mongodb://[username:password@]host1[:port1][,host2[:port2],...[,hostN[:portN]]][/[database][?options]]`
///
/// Supported options include:
///
/// - `authMechanism`: Specifies the authentication mechanism to use, see `ConnectionSettings.Authentication`
/// - `authSource`: The authentication source, see the documenation on `ConnectionSettings.authenticationSource` for details
/// - `ssl`: SSL will be used when set to true
/// - `sslVerify`: When set to `0` or `false`, the SSL certificate will not be verified
/// - `appname`: The application name is printed to the mongod logs upon establishing the connection. It is also recorded in the slow query logs and profile collections.
///
/// For query options, `0`, `false` and `FALSE` are interpreted as false. All other values, including no value at all (when the key is included), are interpreted as true.
public init(_ uri: String) throws {
var uri = uri
let isSRV: Bool
// First, remove the mongodb:// scheme
if uri.starts(with: "mongodb://") {
uri.removeFirst("mongodb://".count)
isSRV = false
} else if uri.starts(with: "mongodb+srv://") {
uri.removeFirst("mongodb+srv://".count)
isSRV = true
} else {
throw MongoInvalidUriError(reason: .missingMongoDBScheme)
}
self.isSRV = isSRV
// Split the string in parts before and after the authentication details
let parts = uri.split(separator: "@")
guard parts.count <= 2, parts.count > 0 else {
throw MongoInvalidUriError(reason: .uriIsMalformed)
}
let uriContainsAuthenticationDetails = parts.count == 2
// The hosts part, for now, is everything after the authentication details
var hostsPart = uriContainsAuthenticationDetails ? parts[1] : parts[0]
var queryParts = hostsPart.split(separator: "?")
hostsPart = queryParts.removeFirst()
let queryString = queryParts.first
// Split the path
let pathParts = hostsPart.split(separator: "/")
hostsPart = pathParts[0]
if pathParts.count > 1 {
self.targetDatabase = String(pathParts[1])
}
// Parse all queries
var queries = [String: String]()
queries.reserveCapacity(10)
if let queryString = queryString {
queryString.split(separator: "&").forEach { queryItem in
// queryItem can be either like `someOption` or like `someOption=abc`
let queryItemParts = queryItem.split(separator: "=", maxSplits: 1)
let queryItemName = String(queryItemParts[0])
let queryItemValue = queryItemParts.count > 1 ? String(queryItemParts[1]) : ""
queries[queryItemName] = queryItemValue.removingPercentEncoding
}
}
self.queryParameters = queries
// Parse the authentication details, if included
if uriContainsAuthenticationDetails {
let authenticationString = parts[0]
let authenticationParts = authenticationString.split(separator: ":")
guard authenticationParts.count == 2 else {
throw MongoInvalidUriError(reason: .malformedAuthenticationDetails)
}
guard let username = authenticationParts[0].removingPercentEncoding, let password = authenticationParts[1].removingPercentEncoding else {
throw MongoInvalidUriError(reason: .malformedAuthenticationDetails)
}
switch queries["authMechanism"]?.uppercased() {
case "SCRAM_SHA_1"?, "SCRAM-SHA-1"?:
self.authentication = .scramSha1(username: username, password: password)
case "SCRAM_SHA_256"?, "SCRAM-SHA-256"?:
self.authentication = .scramSha256(username: username, password: password)
case "MONGODB_CR"?, "MONGODB-CR"?:
self.authentication = .mongoDBCR(username: username, password: password)
case nil:
self.authentication = .auto(username: username, password: password)
default:
throw MongoInvalidUriError(reason: .unsupportedAuthenticationMechanism)
}
} else {
self.authentication = .unauthenticated
}
/// Parse the hosts, which may or may not contain a port number
self.hosts = try hostsPart.split(separator: ",").map { try Host($0, srv: isSRV) }
if hosts.count != 1 && isSRV {
throw MongoInvalidUriError(reason: .srvNeedsOneHost)
}
// Parse various options
self.authenticationSource = queries["authSource"]
if let useSSL = Bool(queryValue: queries["ssl"]) {
self.useSSL = useSSL
} else if let useSSL = Bool(queryValue: queries["tls"]) {
self.useSSL = useSSL
} else if isSRV {
self.useSSL = true
}
if useSSL {
self.sslCaCertificatePath = queries["tlsCAFile"]
// if let insecure = Bool(queryValue: queries["tlsInsecure"]) {
// self.sslDisableValidation = insecure
// }
}
// TODO: Custom root cert for IBM bluemix
if let sslVerify = Bool(queryValue: queries["sslVerify"]) {
self.verifySSLCertificates = sslVerify
}
if let maxConnectionsOption = queries["maxConnections"], let maxConnectionsNumber = Int(maxConnectionsOption), maxConnectionsNumber >= 0 {
self.maximumNumberOfConnections = maxConnectionsNumber
}
if let connectTimeoutMSOption = queries["connectTimeoutMS"], let connectTimeoutMSNumber = Int(connectTimeoutMSOption), connectTimeoutMSNumber > 0 {
self.connectTimeout = TimeInterval(connectTimeoutMSNumber) / 1000
}
if let socketTimeoutMSOption = queries["socketTimeoutMS"], let socketTimeoutMSNumber = Int(socketTimeoutMSOption), socketTimeoutMSNumber > 0 {
self.socketTimeout = TimeInterval(socketTimeoutMSNumber) / 1000
}
self.applicationName = queries["appname"]
self.dnsServer = queries["dnsServer"]
for key in [
"appname",
"dnsServer",
"sslVerify",
"maxConnections",
"connectTimeoutMS",
"socketTimeoutMS",
"tlsCAFile",
"authSource",
"ssl",
"tls",
"authMechanism",
] {
self.queryParameters[key] = nil
}
}
}
| mit | a9630191532b3a8d3ba3a92705e66d77 | 39.771987 | 330 | 0.635216 | 4.941571 | false | false | false | false |
crspybits/SyncServerII | Sources/Server/Database/Files/UploadRepository.swift | 1 | 22759 | //
// UploadRepository.swift
// Server
//
// Created by Christopher Prince on 1/16/17.
//
//
// Persistent Storage for temporarily storing meta data for file uploads and file deletions before finally storing that info in the FileIndex. This also represents files that need to be purged from cloud storage-- this will be for losers of FileIndex update races and for upload deletions.
import Foundation
import SyncServerShared
import LoggerAPI
enum UploadState : String {
case uploadingFile
case uploadedFile
case uploadingUndelete
case uploadedUndelete
case uploadingAppMetaData
case toDeleteFromFileIndex
static func maxCharacterLength() -> Int { return 22 }
}
class Upload : NSObject, Model, Filenaming {
static let uploadIdKey = "uploadId"
var uploadId: Int64!
static let fileUUIDKey = "fileUUID"
var fileUUID: String!
static let userIdKey = "userId"
// The userId of the uploading user. i.e., this is not necessarily the owning user id.
var userId: UserId!
// 3/15/18-- Can now be nil-- when we do an upload app meta data. Keeping it as `!` so it abides by the FileNaming protocol.
static let fileVersionKey = "fileVersion"
var fileVersion: FileVersionInt!
static let deviceUUIDKey = "deviceUUID"
var deviceUUID: String!
static let fileGroupUUIDKey = "fileGroupUUID"
// Not all files have to be associated with a file group.
var fileGroupUUID:String?
// Currently allowing files to be in exactly one sharing group.
static let sharingGroupUUIDKey = "sharingGroupUUID"
var sharingGroupUUID: String!
// The following two dates are required for file uploads.
static let creationDateKey = "creationDate"
var creationDate:Date?
// Mostly for future use since we're not yet allowing multiple file versions.
static let updateDateKey = "updateDate"
var updateDate:Date?
static let stateKey = "state"
var state:UploadState!
static let appMetaDataKey = "appMetaData"
var appMetaData: String?
static let appMetaDataVersionKey = "appMetaDataVersion"
var appMetaDataVersion: AppMetaDataVersionInt?
// This is not present in upload deletions.
static let mimeTypeKey = "mimeType"
var mimeType: String?
// Required only when the state is .uploaded
static let lastUploadedCheckSumKey = "lastUploadedCheckSum"
var lastUploadedCheckSum: String?
subscript(key:String) -> Any? {
set {
switch key {
case Upload.uploadIdKey:
uploadId = newValue as! Int64?
case Upload.fileUUIDKey:
fileUUID = newValue as! String?
case Upload.fileGroupUUIDKey:
fileGroupUUID = newValue as! String?
case Upload.sharingGroupUUIDKey:
sharingGroupUUID = newValue as! String?
case Upload.userIdKey:
userId = newValue as! UserId?
case Upload.fileVersionKey:
fileVersion = newValue as! FileVersionInt?
case Upload.deviceUUIDKey:
deviceUUID = newValue as! String?
case Upload.creationDateKey:
creationDate = newValue as! Date?
case Upload.updateDateKey:
updateDate = newValue as! Date?
case Upload.stateKey:
state = newValue as! UploadState?
case Upload.appMetaDataKey:
appMetaData = newValue as! String?
case Upload.appMetaDataVersionKey:
appMetaDataVersion = newValue as! AppMetaDataVersionInt?
case Upload.mimeTypeKey:
mimeType = newValue as! String?
case Upload.lastUploadedCheckSumKey:
lastUploadedCheckSum = newValue as! String?
default:
Log.error("key: \(key)")
assert(false)
}
}
get {
return getValue(forKey: key)
}
}
func typeConvertersToModel(propertyName:String) -> ((_ propertyValue:Any) -> Any?)? {
switch propertyName {
case Upload.stateKey:
return {(x:Any) -> Any? in
return UploadState(rawValue: x as! String)
}
case Upload.creationDateKey:
return {(x:Any) -> Any? in
return DateExtras.date(x as! String, fromFormat: .DATETIME)
}
case Upload.updateDateKey:
return {(x:Any) -> Any? in
return DateExtras.date(x as! String, fromFormat: .DATETIME)
}
default:
return nil
}
}
}
class UploadRepository : Repository, RepositoryLookup {
private(set) var db:Database!
required init(_ db:Database) {
self.db = db
}
var tableName:String {
return UploadRepository.tableName
}
static var tableName:String {
return "Upload"
}
func upcreate() -> Database.TableUpcreateResult {
let createColumns =
"(uploadId BIGINT NOT NULL AUTO_INCREMENT, " +
// Together, the next three fields form a unique key. The deviceUUID is needed because two devices using the same userId (i.e., the same owning user credentials) could be uploading the same file at the same time.
// permanent reference to file (assigned by app)
"fileUUID VARCHAR(\(Database.uuidLength)) NOT NULL, " +
// reference into User table
// TODO: *2* Make this a foreign reference.
"userId BIGINT NOT NULL, " +
// identifies a specific mobile device (assigned by app)
"deviceUUID VARCHAR(\(Database.uuidLength)) NOT NULL, " +
// identifies a group of files (assigned by app)
"fileGroupUUID VARCHAR(\(Database.uuidLength)), " +
"sharingGroupUUID VARCHAR(\(Database.uuidLength)) NOT NULL, " +
// Not saying "NOT NULL" here only because in the first deployed version of the database, I didn't have these dates. Plus, upload deletions need not have dates. And when uploading a new version of a file we won't give the creationDate.
"creationDate DATETIME," +
"updateDate DATETIME," +
// MIME type of the file; will be nil for UploadDeletion's.
"mimeType VARCHAR(\(Database.maxMimeTypeLength)), " +
// Optional app-specific meta data
"appMetaData TEXT, " +
// 3/25/18; This used to be `NOT NULL` but now allowing it to be NULL because when we upload an app meta data change, it will be null.
"fileVersion INT, " +
// Making this optional because appMetaData is optional. If there is app meta data, this must not be null.
"appMetaDataVersion INT, " +
"state VARCHAR(\(UploadState.maxCharacterLength())) NOT NULL, " +
// Can be null if we create the Upload entry before actually uploading the file.
"lastUploadedCheckSum TEXT, " +
"FOREIGN KEY (sharingGroupUUID) REFERENCES \(SharingGroupRepository.tableName)(\(SharingGroup.sharingGroupUUIDKey)), " +
// Not including fileVersion in the key because I don't want to allow the possiblity of uploading vN of a file and vM of a file at the same time.
// This allows for the possibility of a client interleaving uploads to different sharing group UUID's (without interveneing DoneUploads) -- because the same fileUUID cannot appear in different sharing groups.
"UNIQUE (fileUUID, userId, deviceUUID), " +
"UNIQUE (uploadId))"
let result = db.createTableIfNeeded(tableName: "\(tableName)", columnCreateQuery: createColumns)
switch result {
case .success(.alreadyPresent):
// Table was already there. Do we need to update it?
// Evolution 1: Are creationDate and updateDate present? If not, add them.
if db.columnExists(Upload.creationDateKey, in: tableName) == false {
if !db.addColumn("\(Upload.creationDateKey) DATETIME", to: tableName) {
return .failure(.columnCreation)
}
}
if db.columnExists(Upload.updateDateKey, in: tableName) == false {
if !db.addColumn("\(Upload.updateDateKey) DATETIME", to: tableName) {
return .failure(.columnCreation)
}
}
// 2/25/18; Evolution 2: Remove the cloudFolderName column
let cloudFolderNameKey = "cloudFolderName"
if db.columnExists(cloudFolderNameKey, in: tableName) == true {
if !db.removeColumn(cloudFolderNameKey, from: tableName) {
return .failure(.columnRemoval)
}
}
// 3/23/18; Evolution 3: Add the appMetaDataVersion column.
if db.columnExists(Upload.appMetaDataVersionKey, in: tableName) == false {
if !db.addColumn("\(Upload.appMetaDataVersionKey) INT", to: tableName) {
return .failure(.columnCreation)
}
}
if db.columnExists(Upload.fileGroupUUIDKey, in: tableName) == false {
if !db.addColumn("\(Upload.fileGroupUUIDKey) VARCHAR(\(Database.uuidLength))", to: tableName) {
return .failure(.columnCreation)
}
}
default:
break
}
return result
}
private func haveNilField(upload:Upload, fileInFileIndex: Bool) -> Bool {
// Basic criteria-- applies across uploads and upload deletion.
if upload.deviceUUID == nil || upload.fileUUID == nil || upload.userId == nil || upload.state == nil || upload.sharingGroupUUID == nil {
return true
}
if upload.fileVersion == nil && upload.state != .uploadingAppMetaData {
return true
}
if upload.state == .toDeleteFromFileIndex {
return false
}
if upload.state == .uploadingAppMetaData {
return upload.appMetaData == nil || upload.appMetaDataVersion == nil
}
// We're uploading a file if we get to here. Criteria only for file uploads:
if upload.mimeType == nil || upload.updateDate == nil {
return true
}
// The meta data and version must be nil or non-nil *together*.
let metaDataNil = upload.appMetaData == nil
let metaDataVersionNil = upload.appMetaDataVersion == nil
if metaDataNil != metaDataVersionNil {
return true
}
if !fileInFileIndex && upload.creationDate == nil {
return true
}
if upload.state == .uploadingFile || upload.state == .uploadingUndelete {
return false
}
// Have to have lastUploadedCheckSum when we're in the uploaded state.
return upload.lastUploadedCheckSum == nil
}
enum AddResult: RetryRequest {
case success(uploadId:Int64)
case duplicateEntry
case aModelValueWasNil
case otherError(String)
case deadlock
case waitTimeout
var shouldRetry: Bool {
if case .deadlock = self {
return true
}
if case .waitTimeout = self {
return true
}
else {
return false
}
}
}
// uploadId in the model is ignored and the automatically generated uploadId is returned if the add is successful.
func add(upload:Upload, fileInFileIndex:Bool=false) -> AddResult {
if haveNilField(upload: upload, fileInFileIndex:fileInFileIndex) {
Log.error("One of the model values was nil!")
return .aModelValueWasNil
}
// TODO: *2* Seems like we could use an encoding here to deal with sql injection issues.
let (appMetaDataFieldValue, appMetaDataFieldName) = getInsertFieldValueAndName(fieldValue: upload.appMetaData, fieldName: Upload.appMetaDataKey)
let (appMetaDataVersionFieldValue, appMetaDataVersionFieldName) = getInsertFieldValueAndName(fieldValue: upload.appMetaDataVersion, fieldName: Upload.appMetaDataVersionKey, fieldIsString:false)
let (fileGroupUUIDFieldValue, fileGroupUUIDFieldName) = getInsertFieldValueAndName(fieldValue: upload.fileGroupUUID, fieldName: Upload.fileGroupUUIDKey)
let (lastUploadedCheckSumFieldValue, lastUploadedCheckSumFieldName) = getInsertFieldValueAndName(fieldValue: upload.lastUploadedCheckSum, fieldName: Upload.lastUploadedCheckSumKey)
let (mimeTypeFieldValue, mimeTypeFieldName) = getInsertFieldValueAndName(fieldValue: upload.mimeType, fieldName: Upload.mimeTypeKey)
var creationDateValue:String?
var updateDateValue:String?
if upload.creationDate != nil {
creationDateValue = DateExtras.date(upload.creationDate!, toFormat: .DATETIME)
}
if upload.updateDate != nil {
updateDateValue = DateExtras.date(upload.updateDate!, toFormat: .DATETIME)
}
let (creationDateFieldValue, creationDateFieldName) = getInsertFieldValueAndName(fieldValue: creationDateValue, fieldName: Upload.creationDateKey)
let (updateDateFieldValue, updateDateFieldName) = getInsertFieldValueAndName(fieldValue: updateDateValue, fieldName: Upload.updateDateKey)
let (fileVersionFieldValue, fileVersionFieldName) = getInsertFieldValueAndName(fieldValue: upload.fileVersion, fieldName: Upload.fileVersionKey, fieldIsString:false)
let query = "INSERT INTO \(tableName) (\(Upload.fileUUIDKey), \(Upload.userIdKey), \(Upload.deviceUUIDKey), \(Upload.stateKey), \(Upload.sharingGroupUUIDKey) \(creationDateFieldName) \(updateDateFieldName) \(lastUploadedCheckSumFieldName) \(mimeTypeFieldName) \(appMetaDataFieldName) \(appMetaDataVersionFieldName) \(fileVersionFieldName) \(fileGroupUUIDFieldName)) VALUES('\(upload.fileUUID!)', \(upload.userId!), '\(upload.deviceUUID!)', '\(upload.state!.rawValue)', '\(upload.sharingGroupUUID!)' \(creationDateFieldValue) \(updateDateFieldValue) \(lastUploadedCheckSumFieldValue) \(mimeTypeFieldValue) \(appMetaDataFieldValue) \(appMetaDataVersionFieldValue) \(fileVersionFieldValue) \(fileGroupUUIDFieldValue));"
if db.query(statement: query) {
return .success(uploadId: db.lastInsertId())
}
else if db.errorCode() == Database.deadlockError {
return .deadlock
}
else if db.errorCode() == Database.lockWaitTimeout {
return .waitTimeout
}
else if db.errorCode() == Database.duplicateEntryForKey {
return .duplicateEntry
}
else {
let error = db.error
let message = "Could not insert into \(tableName): \(error)"
Log.error(message)
return .otherError(message)
}
}
// The Upload model *must* have an uploadId
func update(upload:Upload, fileInFileIndex:Bool=false) -> Bool {
if upload.uploadId == nil || haveNilField(upload: upload, fileInFileIndex:fileInFileIndex) {
Log.error("One of the model values was nil!")
return false
}
// TODO: *2* Seems like we could use an encoding here to deal with sql injection issues.
let appMetaDataField = getUpdateFieldSetter(fieldValue: upload.appMetaData, fieldName: Upload.appMetaDataKey)
let lastUploadedCheckSumField = getUpdateFieldSetter(fieldValue: upload.lastUploadedCheckSum, fieldName: Upload.lastUploadedCheckSumKey)
let mimeTypeField = getUpdateFieldSetter(fieldValue: upload.mimeType, fieldName: Upload.mimeTypeKey)
let fileGroupUUIDField = getUpdateFieldSetter(fieldValue: upload.fileGroupUUID, fieldName: Upload.fileGroupUUIDKey)
let query = "UPDATE \(tableName) SET fileUUID='\(upload.fileUUID!)', userId=\(upload.userId!), fileVersion=\(upload.fileVersion!), state='\(upload.state!.rawValue)', deviceUUID='\(upload.deviceUUID!)' \(lastUploadedCheckSumField) \(appMetaDataField) \(mimeTypeField) \(fileGroupUUIDField) WHERE uploadId=\(upload.uploadId!)"
if db.query(statement: query) {
// "When using UPDATE, MySQL will not update columns where the new value is the same as the old value. This creates the possibility that mysql_affected_rows may not actually equal the number of rows matched, only the number of rows that were literally affected by the query." From: https://dev.mysql.com/doc/apis-php/en/apis-php-function.mysql-affected-rows.html
if db.numberAffectedRows() <= 1 {
return true
}
else {
Log.error("Did not have <= 1 row updated: \(db.numberAffectedRows())")
return false
}
}
else {
let error = db.error
Log.error("Could not update \(tableName): \(error)")
return false
}
}
enum LookupKey : CustomStringConvertible {
case uploadId(Int64)
case fileUUID(String)
case userId(UserId)
case filesForUserDevice(userId:UserId, deviceUUID:String, sharingGroupUUID: String)
case primaryKey(fileUUID:String, userId:UserId, deviceUUID:String)
var description : String {
switch self {
case .uploadId(let uploadId):
return "uploadId(\(uploadId))"
case .fileUUID(let fileUUID):
return "fileUUID(\(fileUUID))"
case .userId(let userId):
return "userId(\(userId))"
case .filesForUserDevice(let userId, let deviceUUID, let sharingGroupUUID):
return "userId(\(userId)); deviceUUID(\(deviceUUID)); sharingGroupUUID(\(sharingGroupUUID))"
case .primaryKey(let fileUUID, let userId, let deviceUUID):
return "fileUUID(\(fileUUID)); userId(\(userId)); deviceUUID(\(deviceUUID))"
}
}
}
func lookupConstraint(key:LookupKey) -> String {
switch key {
case .uploadId(let uploadId):
return "uploadId = '\(uploadId)'"
case .fileUUID(let fileUUID):
return "fileUUID = '\(fileUUID)'"
case .userId(let userId):
return "userId = '\(userId)'"
case .filesForUserDevice(let userId, let deviceUUID, let sharingGroupUUID):
return "userId = \(userId) and deviceUUID = '\(deviceUUID)' and sharingGroupUUID = '\(sharingGroupUUID)'"
case .primaryKey(let fileUUID, let userId, let deviceUUID):
return "fileUUID = '\(fileUUID)' and userId = \(userId) and deviceUUID = '\(deviceUUID)'"
}
}
func select(forUserId userId: UserId, sharingGroupUUID: String, deviceUUID:String, andState state:UploadState? = nil) -> Select? {
var query = "select * from \(tableName) where userId=\(userId) and sharingGroupUUID = '\(sharingGroupUUID)' and deviceUUID='\(deviceUUID)'"
if state != nil {
query += " and state='\(state!.rawValue)'"
}
return Select(db:db, query: query, modelInit: Upload.init, ignoreErrors:false)
}
enum UploadedFilesResult {
case uploads([Upload])
case error(Swift.Error?)
}
// With nil `andState` parameter value, returns both file uploads and upload deletions.
func uploadedFiles(forUserId userId: UserId, sharingGroupUUID: String, deviceUUID: String, andState state:UploadState? = nil) -> UploadedFilesResult {
guard let selectUploadedFiles = select(forUserId: userId, sharingGroupUUID: sharingGroupUUID, deviceUUID: deviceUUID, andState: state) else {
return .error(nil)
}
var result:[Upload] = []
selectUploadedFiles.forEachRow { rowModel in
let rowModel = rowModel as! Upload
result.append(rowModel)
}
if selectUploadedFiles.forEachRowStatus == nil {
return .uploads(result)
}
else {
return .error(selectUploadedFiles.forEachRowStatus!)
}
}
static func uploadsToFileInfo(uploads: [Upload]) -> [FileInfo] {
var result = [FileInfo]()
for upload in uploads {
let fileInfo = FileInfo()
fileInfo.fileUUID = upload.fileUUID
fileInfo.fileVersion = upload.fileVersion
fileInfo.deleted = upload.state == .toDeleteFromFileIndex
fileInfo.mimeType = upload.mimeType
fileInfo.creationDate = upload.creationDate
fileInfo.updateDate = upload.updateDate
fileInfo.fileGroupUUID = upload.fileGroupUUID
fileInfo.sharingGroupUUID = upload.sharingGroupUUID
result += [fileInfo]
}
return result
}
static func isValidAppMetaDataUpload(currServerAppMetaDataVersion: AppMetaDataVersionInt?, currServerAppMetaData: String?, optionalUpload appMetaData:AppMetaData?) -> Bool {
if appMetaData == nil {
// Doesn't matter what the current app meta data is-- we're not changing it.
return true
}
else {
return isValidAppMetaDataUpload(currServerAppMetaDataVersion: currServerAppMetaDataVersion, currServerAppMetaData: currServerAppMetaData, upload: appMetaData!)
}
}
static func isValidAppMetaDataUpload(currServerAppMetaDataVersion: AppMetaDataVersionInt?, currServerAppMetaData: String?, upload appMetaData:AppMetaData) -> Bool {
if currServerAppMetaDataVersion == nil {
// No app meta data yet on server for this file. Need 0 first version.
return appMetaData.version == 0
}
else {
// Already have app meta data on server-- must have next version.
return appMetaData.version == currServerAppMetaDataVersion! + 1
}
}
}
| mit | a36b9854ff6f1062aa51a91a01dfd472 | 41.146296 | 724 | 0.615669 | 5.008583 | false | false | false | false |
zaneswafford/DrawerViewController | DrawerDemo/DrawerContainerViewController.swift | 1 | 5321 | //
// DrawerContainerViewController.swift
// DrawerDemo
//
// Created by Zane Swafford on 2/9/15.
// Copyright (c) 2015 Zane Swafford. All rights reserved.
//
import UIKit
import QuartzCore
let MAIN_STORYBOARD_IDENTIFIER = "Main"
let DRAWER_PANEL_VIEW_CONTROLLER_IDENTIFIER = "DrawerPanelViewController"
let DRAWER_VIEW_CONTROLLER_IDENTIFIER = "DrawerViewController"
enum DrawerState {
case Open
case Closed
}
class DrawerContainerViewController: UIViewController, DrawerViewControllerDelegate, UIGestureRecognizerDelegate {
var drawerNavigationController: UINavigationController!
var drawerViewController: DrawerViewController!
var drawerPanelViewController: DrawerPanelViewController?
let centerPanelExpandedOffset: CGFloat = 60
var currentState: DrawerState = .Closed {
didSet {
let shouldShowShadow = currentState != .Closed
showShadowForDrawerViewController(shouldShowShadow)
}
}
override func viewDidLoad() {
super.viewDidLoad()
drawerViewController = UIStoryboard.drawerViewController()
drawerViewController.delegate = self
drawerNavigationController = UINavigationController(rootViewController: drawerViewController)
view.addSubview(drawerNavigationController.view)
addChildViewController(drawerNavigationController)
drawerNavigationController.didMoveToParentViewController(self)
let panGestureRecognizer = UIPanGestureRecognizer(target: self, action: "handlePanGesture:")
drawerNavigationController.view.addGestureRecognizer(panGestureRecognizer)
}
func toggleDrawer() {
let notAlreadyOpened = (currentState != .Open)
if notAlreadyOpened {
addDrawerPanelViewController()
}
animateDrawerPanel(shouldOpen: notAlreadyOpened)
}
func addDrawerPanelViewController() {
if (drawerPanelViewController == nil) {
drawerPanelViewController = UIStoryboard.drawerPanelViewController()
drawerPanelViewController!.delegate = drawerViewController
view.insertSubview(drawerPanelViewController!.view, atIndex: 0)
addChildViewController(drawerPanelViewController!)
drawerPanelViewController!.didMoveToParentViewController(self)
}
}
func animateDrawerPanel(#shouldOpen: Bool) {
if (shouldOpen) {
currentState = .Open
animateDrawerViewControllerXPosition(targetPosition: CGRectGetWidth(drawerNavigationController.view.frame) - centerPanelExpandedOffset)
} else {
animateDrawerViewControllerXPosition(targetPosition: 0) { finished in
self.currentState = .Closed
self.drawerPanelViewController!.view.removeFromSuperview()
self.drawerPanelViewController = nil;
}
}
}
func animateDrawerViewControllerXPosition(#targetPosition: CGFloat, completion: ((Bool) -> Void)! = nil) {
UIView.animateWithDuration(0.5, delay: 0, usingSpringWithDamping: 0.8, initialSpringVelocity: 0, options: .CurveEaseInOut, animations: {
self.drawerNavigationController.view.frame.origin.x = targetPosition
}, completion: completion)
}
func showShadowForDrawerViewController(shouldShowShadow: Bool) {
if (shouldShowShadow) {
drawerNavigationController.view.layer.shadowOpacity = 0.8
} else {
drawerNavigationController.view.layer.shadowOpacity = 0.0
}
}
// MARK: UIPanGestureRecognizer
func handlePanGesture(recognizer: UIPanGestureRecognizer) {
let gestureIsDraggingFromLeftToRight = (recognizer.velocityInView(view).x > 0)
switch(recognizer.state) {
case .Began:
if (currentState == .Closed) {
addDrawerPanelViewController()
showShadowForDrawerViewController(true)
}
case .Changed:
let translation = recognizer.view!.frame.origin.x + recognizer.translationInView(view).x
if translation >= 0 {
recognizer.view!.frame.origin.x = translation
recognizer.setTranslation(CGPointZero, inView: view)
}
case .Ended:
if (drawerPanelViewController != nil) {
let hasMovedGreaterThanHalfway = recognizer.view!.center.x > view.bounds.size.width
animateDrawerPanel(shouldOpen: hasMovedGreaterThanHalfway)
}
default:
break
}
}
}
private extension UIStoryboard {
class func mainStoryboard() -> UIStoryboard { return UIStoryboard(name: MAIN_STORYBOARD_IDENTIFIER, bundle: NSBundle.mainBundle()) }
class func drawerPanelViewController() -> DrawerPanelViewController? {
return mainStoryboard().instantiateViewControllerWithIdentifier(DRAWER_PANEL_VIEW_CONTROLLER_IDENTIFIER) as? DrawerPanelViewController
}
class func drawerViewController() -> DrawerViewController? {
return mainStoryboard().instantiateViewControllerWithIdentifier(DRAWER_VIEW_CONTROLLER_IDENTIFIER) as? DrawerViewController
}
}
| bsd-3-clause | bd538021beee9a8b43b480d930a21623 | 37.557971 | 147 | 0.67882 | 5.83443 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.